静态属性


In [5]:
class Person():
    age = 10

x = Person()

print(Person.age)  #静态变量可以直接用
print(x.age)

Person.age = 20    #直接更改静态变量会对其实例参数影响
print(x.age)

x.age = 30         #在实例中更改静态变量只会对实例内部的静态变量产生影响
print(Person.age)


10
10
20
20

In [6]:
class Person():
    @classmethod    #静态方法
    def method(self):
        print("hello")
Person.method()


hello

委托

在c#中委托是指指向某个函数的一个变量,事实上就是在某个对象中内嵌入其他对象,以实现请求的传递

在python中委托是通过getattr实现的


In [2]:
class wrapper:
    def __init__(self,object):
        self.wrapped = object
    def __getattr__(self,attrname):
        print("trace",attrname)
        return getattr(self.wrapped,attrname)
a = wrapper([1,2,3])
a.append(3)      #a.append(3)转化成 self.wrapped.append(3) 
a.wrapped        #getattr(X,N)会执行X.N


trace append
Out[2]:
[1, 2, 3, 3]

伪私有属性


In [11]:
#使用伪私有属性主要是避免实例内部命名冲突
class c1:
    def meth1(self):
        self.x = 88
class c2:
    def metha(self):
        self.x = 99
class c3(c1,c2):
    pass
a = c3()
a.meth1()
a.metha()    #这里两个类中都有x这样就会出现冲突
print(a.x)


99

In [15]:
class c1:
    def meth1(self):
        self.__x = 88
class c2:
    def metha(self):
        self.__x = 99
class c3(c1,c2):
    pass
a = c3()
a.meth1()
a.metha()   #在这里,x会自动扩充为_c2__x和_c1__x
print(a._c2__x,a._c1__x)  #正常输出

print(a.x)  #报错


99 88
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-15-6e0230393033> in <module>()
     12 print(a._c2__x,a._c1__x)  #正常输出
     13 
---> 14 print(a.x)  #报错

AttributeError: 'c3' object has no attribute 'x'

工厂类


In [16]:
def factory(aClass,*args):
    return aClass(*args)

class People:
    def __init__(self,name):
        self.name = name
        print(name)
a = factory(People,"aa")   #工厂式输出一个类


aa

In [ ]: