属性访问
# 类属性是公共的,所有方法内部均能够访问到;静态方法不需要访问类属性,因为静态方法和类、对象没有关联;实例属性是私有的,只有实例方法内部能够访问到
多态
# 多态的特点:
# 1. 不关注对象的类型,关注对象具有的行为,也就是对象的实例方法是否同名。
# 2. 优点:可以增加代码的外部调用灵活度,让代码更加通用,兼容性比较强。
# 3. 不同的子类对象,调用相同的父类方法,会产生不同的执行结果。
class father():
def func1(self):
print("father")
class child1(father):
def func1(self):
print("child1")
class child2(father):
def func1(self):
print("child2")
多态性
# 多态性:一种调用方式,可以执行不同的结果
def func(obj): # 传入不同实例,均执行实例的funct函数
obj.funct()
静态方法
# 静态方法:使用@staticmethod来进行修饰,静态方法没有self,cls的限制
# 静态方法与类无关,可以被转换成函数使用;既可以用对象方法,也可以使用类访问
class A(object):
def func1(self):
pass
@staticmethod
def func2():
print("这是静态方法")
A.func2()
A1 = A()
A1.func2()
类方法
# 类方法:使用装饰器@classmethod来表示为类方法,对于类方法,第一个参数必须为类对象,一般以cls作为第一个参数
# 类方法内部,可以访问类属性,或者调用其他的类方法;一般只配合类属性使用
# cls:表示类对象本身
class B(object):
name="B"
@classmethod
def fun1(cls):
print(cls)
print(cls.name)
B.fun1()