class Beartoy: #新建一个类
def __init__(self, name, size, color): #定义方法,用于创建实例用
self.name = name
self.size = size
self.color = color
if __name__ == '__main__':
b1 = Beartoy('Tidy', 'middle', 'yellow') #创建一个实例
print(b1.name, b1.size, b1.color) #调用实例
1、定义一个类,在类里面是明确了类方法,方法为init
2、调用的时候,必须要先创建一个实例。然后调用实例。
class Beartoy:
def __init__(self, name, size, color):
self.name = name
self.size = size
self.color = color
def say_hi(self): #归属在Beartoy这个类下面的一个方法
print('Hello World!!')
if __name__ == '__main__':
b1 = Beartoy('Tidy', 'middle', 'yellow')
print(b1.name, b1.size, b1.color)
b1.say_hi() #已创建实例,直接调用方法
1、由于归属在Beartoy这个类下面,无需再定义类
2、自定义的一个方法‘say_hi’,由于已创建实例,所以直接调用
class HotelBase:
def __init__(self, baseroom=100, discount=1.0, breakfast=15):
self.baseroom = baseroom
self.discount = discount
self.breakfast = breakfast
def days(self, days=1):
return (self.baseroom * self.discount + self.breakfast) * days
if __name__ == '__main__':
baseroom = HotelBase() #新建实例
b = baseroom.days(10) #调用实例
print(b)
staroom = HotelBase(198, 0.9, 15) #新建实例
s = staroom.days(10) #调用实例
print(s)
这里实现一个小程序,酒店记录的。
基础房间是100.折扣是1.0折,早餐是15.把这些固定基础属性写到类里面。然后新建一个传入天数的方法,然后返回计算结果的return。‘
如果不传入参数,默认为base房间。如果传入了完整的参数,例如标准间的参数,就会计算出标准间的结果。
class BearBase:
def __init__(self, model, size, color):
self.model = model
self.size = size
self.color = color
def sing(self):
print('my color is %s, i can sing:lalala......' % self.color)
class BearRed:
def __init__(self, product, status, model, size, color): #与其他类组合,需要补充参数
self.product = product
self.status = status
self.model = BearBase(model, size, color) #与其他类组合,可以调用其他类
def run(self): #但类之间函数是不通用
print('my product is %s, i can run......' % self.product)
if __name__ == '__main__':
r = BearRed('henan', 'saled', 'A1567', 'middle', 'red')
r.model.sing() #从BearRed类中直接调用其他类
类之间可以组合使用。需要补充完毕其他类的参数。但有一点,A类是无法直接使用B类的函数?????这里我没懂为什么。
class BearBase:
def __init__(self, model, size, color):
self.model = model
self.size = size
self.color = color
def sing(self):
print('my color is %s, i can sing:lalala......' % self.color)
class BearRed(BearBase): #以BearBase为父类(基类)
def __init__(self, product, status, model, size, color):
self.product = product
self.status = status
BearBase.__init__(self, model, size, color) #父类实例化
def run(self):
print('my product is %s, i can run......' % self.model) #可使用父类的参数
if __name__ == '__main__':
r = BearRed('henan', 'saled', 'A1567', 'middle', 'yellow')
r.run()
r.sing()
这种用法是父类(基类)的继承。如图所示,采用这种方法,可以使得可用参数变多。
class Abc:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return 'i am %s,i am %d' % (self.name, self.age)
class Cde:
def __init__(self, work, comp):
self.work = work
self.comp = comp
def __call__(self, *args, **kwargs):
print('my work is %s, i am in %s work' % (self.work, self.comp))
if __name__ == '__main__':
a = Abc('bob', 25)
d = Cde('teacher', 'huahuaxiaoxue')
print(a)
d()
三种magic方法的使用。初始化:实现实例的创建,字符化:实现返回值为字符串,可调用化:实现类的调用