1、https://py.eastlakeside.cn/book/DataStructures/classes.html 2、https://mofanpy.com/tutorials/python-basic/interactive-python/class/
通常约定类的首字母要大写
self是作为类自己的一个索引,不管你在定义类的时候,想要获取这个类的什么属性或功能,都可以通过self来获取
实例变量与类变量
实例变量用于每个对象是唯一的数据
类变量用于在类的不同实例之间共享的数据
class Cal(object):# pi 是类变量pi = 3.142def __init__(self, radius):# self.radius 是实例变量self.radius = radiusdef area(self):return self.pi * (self.radius ** 2)a = Cal(32)a.area()# Output: 3217.408a.pi# Output: 3.142a.pi = 43a.pi# Output: 43b = Cal(44)b.area()# Output: 6082.912b.pi# Output: 3.142b.pi = 50b.pi# Output: 50
class SuperClass(object):superpowers = []def __init__(self, name):self.name = namedef add_superpower(self, power):self.superpowers.append(power)foo = SuperClass('foo')bar = SuperClass('bar')foo.name# Output: 'foo'bar.name# Output: 'bar'foo.add_superpower('fly')bar.superpowers# Output: ['fly']foo.superpowers# Output: ['fly']
魔术方法
__init__
是一个类初始化器,每当类创建一个类实例时,都会调用其__init__方法,例如:
class GetTest(object):def __init__(self):print('Greetings!!')def another_method(self):print('I am another method which is not'' automatically called')a = GetTest()# Output: Greetings!!a.another_method()# Output: I am another method which is not automatically# called
在创建实例后会立即调用**__init__**,还可以在初始化期间将参数传递给类
class GetTest(object):def __init__(self, name):print('Greetings!! {0}'.format(name))def another_method(self):print('I am another method which is not'' automatically called')a = GetTest('yasoob')# Output: Greetings!! yasoob# Try creating an instance without the name argumentsb = GetTest()Traceback (most recent call last):File "<stdin>", line 1, in <module>TypeError: __init__() takes exactly 2 arguments (1 given)
__getitem__
class GetTest(object):def __init__(self):self.info = {'name':'Yasoob','country':'Pakistan','number':12345812}def __getitem__(self,i):return self.info[i]foo = GetTest()foo['name']# Output: 'Yasoob'foo['number']# Output: 12345812
继承
定义文本文件和视频文件,如果分开定义两个类,可以这样写:
class Video:def __init__(self, name, window_size=(1080, 720)):self.name = nameself.window_size = window_sizeself.create_time = "today"class Text:def __init__(self, name, language="zh-cn"):self.name = nameself.language = languageself.create_time = "today"
这两个文件其实是有共性的,比如都有name
它们可以抽象出一个更底层的类,也就是“文件类”。这个类包含了属于文件所具备的共同属性和功能
可以通过继承的方式,将细分类嵌入到抽象类中,减少共有属性/功能的重复开发
class File:def __init__(self,name,create_time="today"):self.name = nameself.create_time = create_timedef get_info(self):return self.name + "is create at " + self.create_timeclass Video(File): #继承了File的属性和方法def __init__(self,name,window_size=(1080,720)):#将公用属性的设置导入super.__init__(name=name,create_time="today")self.window_size = window_sizeclass Text(File):def __init__(self,name,language="zh-cn"):super().__init__(name=name,create_time="today")self.language = languagedef get_more_info(self):return self.get_info()+", using language of " + self.languagev = Video("my_video")t = Text("my_text")print(v.get_info()) #调用父类的功能print(t.create_time) #调用父类的属性
