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)
In [6]:
class Person():
@classmethod #静态方法
def method(self):
print("hello")
Person.method()
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
Out[2]:
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)
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) #报错
In [16]:
def factory(aClass,*args):
return aClass(*args)
class People:
def __init__(self,name):
self.name = name
print(name)
a = factory(People,"aa") #工厂式输出一个类
In [ ]: