新建一个类
#create a new class
class Cola:
formula = ['sugar','water','soda']
类的属性
Cola.formula
>>> ['sugar','water','soda']
类里的变量称为Class Atrribute(类的属性)
类的实例化
coke = Cola()
类属性引用
#两种结果一样
Cola.formula
coke.formula
实例属性
class Cola:
formula = [‘sugar','water','soda']
coke_China = Cola()
coke_China.local_logo = '可乐'
print(coke_China.local_logo)
实例方法
class Cola:
formula = ['sugar','water','soda']
def drink(self):
print('Full!')
coke = CocaCola()
coke.drink()
>>> Full!
对比一下:
class Cola:
formula = ['sugar','water','soda']
def drink(coke): # HEREѺ
print('Full!')
coke = Cola()
coke.drink()
>>> Full!
另一个对比:
coke = Cola
coke.drink() == Cola.drink(coke)
self是实例对象的参数名,可以改,习惯用self
另一个例子:
class BuildRobot():
def __init__(self,armcount,headcount):
self.armcount = armcount
self.headcount = headcount
这里def __init__(self,armcount,headcount):
为类的初始化操作
armcount,headcount
为BuildRoot
类里面的初始属性。必要参数。
调用类里函数的方法:
class Cola:
formula = ['sugar','water','soda']
def drink(self,how_much):
if how_much == 'a sip':
print('Cool~')
elif how_much == 'whole bottle'
print('HaHa!')
ice_coke = CocaCola()
ice_coke.drink('a sip')
>>> Cool~