版权声明:转载请注明出处~ 摸摸博主狗头 https://blog.csdn.net/cris_zz/article/details/83817271
1、类属性,实例属性,实例方法,类方法,静态方法
class A(object):
'''
类属性:定义并初始化在类中,可以通过类和实例去访问,但是只能通过类修改
实例可以使用同名的实例属性进行覆盖
'''
country = "China"
def __init__(self):
# 实例属性:只能通过实例访问和修改,只属于某个特定的实例,类无法访问和修改
self.name = "cris"
# 实例方法:类中定义并且以 self 处于第一个参数位置,该方法被调用时,自动将调用该参数的实例传入作为第一个参数
# 也可以通过类去调用
def test(self):
print("test!")
# 类方法:使用 @classmethod 注解的方法,类方法的第一个参数默认定义为 cls,就是当前的 class 对象
# 可以通过类或者实例去调用
@classmethod
def function(cls):
print("this is class method", cls)
# 静态方法:不需要指定默认参数,也不会自动传递,可以通过类和实例调用
# 只是保存到当前类的一个函数,和当前类关系不大,一般作为工具方法
@staticmethod
def haha():
print('static method')
print(A.country) # China
a = A()
print(a.country) # China
a.country = 'Japan'
print(A.country) # China
print(a.country) # Japan
a.test() # test!
# A.test() # 报错
A.test(a) # test!
A.function() # this is class method <class '__main__.A'>
a.haha() # static method
2、垃圾回收和特殊/魔术方法
# 没有变量指向的对象可以称之为垃圾,Python 会自动将其销毁,并且调用对象的 __del__ 方法
class A(object):
def __del__(self):
print(f'{self} is deleting~')
a = A()
a = None # <__main__.A object at 0x0000026FD678B0F0> is deleting~
# 特殊方法(魔术方法):__ 开头,__ 结尾
# 一般不需要我们手动调用,一般都是自动调用
class Student(object):
# 初始化方法
def __init__(self, name, age):
self._name = name
self._age = age
# 类似 Java 的toString 方法,打印对象时被调用
def __str__(self):
return f'{self._name} --- {self._age}'
# 对当前对象使用repr 函数时调用:指定对象在交互模式中输出的结果
def __repr__(self):
return "hehe"
# 大于方法
def __gt__(self, other):
return self._age > other._age
# 小于
def __lt__(self, other):
return self._age > other._age
def __bool__(self):
return self._age > 20
'''
__eq__;__ge__;__le__;__ne__;
__len__(self):获取长度
__bool__(self):返回 bool 类型的数据,可以用于自定义判断(用于 if 语句)
# object.__add__(self, other)
# object.__sub__(self, other)
# object.__mul__(self, other)
# object.__matmul__(self, other)
# object.__truediv__(self, other)
# object.__floordiv__(self, other)
# object.__mod__(self, other)
# object.__divmod__(self, other)
# object.__pow__(self, other[, modulo])
# object.__lshift__(self, other)
# object.__rshift__(self, other)
# object.__and__(self, other)
# object.__xor__(self, other)
# object.__or__(self, other)
'''
s1 = Student('cris', 16)
s2 = Student('james', 22)
print(s2) # <__main__.Student object at 0x000002BF08408A20>
print(s2) # james --- 22
print(s1 > s2) # False
print(s2 > s1) # True
print(bool(s1)) # False
print(bool(s2)) # True