类变量 & 实例变量
self 代表的是类的实例,代表当前对象的地址,而 self.class 则指向类
class Test:
w = 10
def __init__(self, k):
Test.h = 50
self.k = k
def prt(self):
print(self)
print(self.__class__)
a = Test(1)
'''
print(dir(Test))
print(Test.__dict__)
print(dir(a))
print(a.__dict__)
'''
print("1", Test.w, id(Test.w), Test.h, id(Test.h))
print("2", a.w, id(a.w))
a.w = 100
print("3", a.w, id(a.w))
a.w = 200
print("4", a.w, id(a.w))
Test.h = 500
print("5", Test.h, id(Test.h))
b = Test(2)
print("6", Test.h, id(Test.h))
print("7", b.k, id(b.k))
Test.t = 'Hello'
b.t = "Python"
'''
print(dir(Test))
print(Test.__dict__)
print(dir(b))
print(b.__dict__)
'''
print("8", Test.t, id(Test.t), b.t, id(b.t))
del Test.t
print("9", b.t, id(b.t))
a.prt()
类属性 & 方法
类方法 & 静态方法 & 实例方法
- 采用
@classmethod 修饰的方法为类方法; - 采用
@staticmethod 修饰的方法为静态方法; - 不用任何修改的方法为实例方法。
class Site:
def __init__(self, name, url):
self.name = name
self.__url = url
def who(self):
print('name: ', self.name)
print('url: ', self.__url)
def __foo(self):
print('这是私有方法')
def foo(self):
print('这是公共方法')
self.__foo()
x = Site('菜鸟教程', 'www.runoob.com')
x.who()
x.foo()
x.__foo()
print(x.__url)
类的专有方法: __init__ : 构造函数,在生成对象时调用 __del__ : 析构函数,释放对象时使用 __repr__ : 打印,转换 __setitem__ : 按照索引赋值 __getitem__: 按照索引获取值 __len__: 获得长度 __cmp__: 比较运算 __call__: 函数调用 __sub__: 减运算 __mul__: 乘运算 __truediv__: 除运算 __mod__: 求余运算 __pow__: 乘方运算
继承
super() 函数是用来调用父类的一个方法。在多继承中使用时,需要考虑 MRO(即Method Resolution Order)的问题。super() 函数获取的是 MRO 列表中的下一个类。
class A(object):
def __init__(self):
self.n = 10
def minus(self, m):
print('minus in class A start',
' self is {0} @A.minus.format(self)'.format(self))
self.n -= m
print('minus in class A end', " self.n=", self.n)
class B(A):
def __init__(self):
self.n = 7
def minus(self, m):
print('minus in class B start',
' self is {0} @B.minus.format(self)'.format(self))
super(B, self).minus(m)
self.n -= 2
print('minus in class B end', " self.n=", self.n)
class C(A):
def __init__(self):
self.n = 12
def minus(self, m):
print('minus in class C start',
' self is {0} @C.minus.format(self)'.format(self))
super(C, self).minus(m)
self.n -= 5
print('minus in class C end', " self.n=", self.n)
class D(B, C):
def __init__(self):
self.n = 15
def minus(self, m):
print('minus in class D start',
' self is {0} @D.minus.format(self)'.format(self))
super(D, self).minus(m)
self.n -= 2
print('minus in class D end', " self.n=", self.n)
print('The MRO of class D is :', D.__mro__)
d = D()
d.minus(2)
print(d.n)
运算符重载
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector(%d, %d)' % (self.a, self.b)
def __add__(self, other):
return Vector(self.a+other.a, self.b+other.b)
v1 = Vector(2, 10)
v2 = Vector(5, -2)
print(v1+v2)
|