Table of Contents
类和对象
class的属性和方法
类的首字母大写
一个人名字和年级是属性,而他的行为可以看成方法,
如下中 name age 是属性,打招呼为方法
class Man:
name = 'xiaohong'
age = 20
def hello(self):
print(f'my name is {self.name}, i am {self.age}')
man_1 = Man()
man_1.hello()
my name is xiaohong, i am 20
self表示本身,在上面中self值得就是man_1,其参数也可修改
man_1.name = 'xiaojaing'
man_1.age = 90
man_1.hello()
my name is xiaojaing, i am 90
init
每当你根据类创建新实例时,Python都会自动运行它。
class woman:
def __init__(self,):
self.name = 'xiaohong'
self.age = 15
def hello(self):
print(f'my name is {self.name}, i am {self.age}')
woman().hello()
my name is xiaohong, i am 15
class woman:
def __init__(self,name,age):
self.name = name
self.age = age
def hello(self):
print(f'my name is {self.name}, i am {self.age}')
woman('xiaoli',50).hello()
my name is xiaoli, i am 50
class Dog():
"""一次模拟小狗的简单尝试"""
def __init__(self, name, age):
"""初始化属性name和age"""
self.name = name
self.age = age
def sit(self):
"""模拟小狗被命令时蹲下"""
print(self.name.title() + " is now sitting.")
def roll_over(self):
"""模拟小狗被命令时打滚"""
print(self.name.title() + " rolled over!")
Dog('a',15).sit()
A is now sitting.
iter 和 next
__iter()__方法返回迭代器对象本身
__next()__方法返回容器的下一个元素,在没有后续元素时会抛出StopIteration异常。
class Fib():
def __init__(self):
self.a, self.b = 0, 1
def __iter__(self):
return self
def __next__(self):
self.a, self.b = self.b, self.a + self.b
return self.a
fib = Fib()
for i in fib:
if i > 10:
break
print(i)# 1, 1, 2, 3, 5, 8
1
1
2
3
5
8
继承
编写类时,并非总是要从空白开始。如果你要编写的类是另一个现成类的特殊版本,可使用继承 。一个类继承 另一个类时,它将自动获得另一个类的所有属性和方法;原有的类称为父类 ,而新类称为子类 。子类继承了其父类的所有属性和方法,同时还可以定义自己的属性和方法。
如果子类中定义与父类同名的方法或属性,则会自动覆盖父类对应的方法或属性。
class people:
def __init__(self, n, a, w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s 说: 我 %d 岁。" % (self.name, self.age))
def hello(self):
print(self.name ,self.age)
# 单继承示例
class student(people):
grade = ''
def __init__(self, n, a, w, g):
# 调用父类的构函
people.__init__(self, n, a, w)
self.grade = g
# 覆写父类的方法
def speak(self):
print("%s 说: 我 %d 岁了,我在读 %d 年级" % (self.name, self.age, self.grade))
s = student('小马的程序人生', 10, 60, 3)
s.speak()
s.hello()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-48-285bf87c1fea> in <module>
26
27 s = student('小马的程序人生', 10, 60, 3)
---> 28 s.speak()
29 s.hello()
<ipython-input-48-285bf87c1fea> in speak(self)
22 # 覆写父类的方法
23 def speak(self):
---> 24 print("%s 说: 我 %d 岁了,我在读 %d 年级" % (self.name, self.age, self.grade))
25
26
AttributeError: 'student' object has no attribute 'name'
speak覆盖之前父类的
hello更新 ,类似update
多态
指对不同类型的参数进行相同的操作,根据对象(或类)类型的不同而表现出不同的行为。继承可以拿到父类的所有数据和方法,子类可以重写父类的方法,也可以新增自己特有的方法。有了继承,才有了多态,这样才能实现为不同的数据类型的实体提供统一的接口。
class Animal():
def __init__(self, name):
self.name = name
def greet(self):
print(f'Hello, I am {self.name}.')
class Dog(Animal):
def greet(self):
print(f'WangWang.., I am {self.name}.')
class Cat(Animal):
def greet(self):
print(f'MiaoMiao.., I am {self.name}')
def hello(animal):
animal.greet()
dog = Dog('wangwang')
cat = Cat('mimi')
hello(dog),hello(cat)
WangWang.., I am wangwang.
MiaoMiao.., I am mimi
(None, None)
练习
4、按照以下要求定义一个游乐园门票的类,并尝试计算2个成人+1个小孩平日票价。
要求:
平日票价100元
周末票价为平日的120%
儿童票半价
class Ticket():
def __init__(self,adult_n,children_n,weekday):
self.adult_n = adult_n
self.children_n = children_n
self.weekday = weekday
def price(self):
p = (self.weekday*0.2 + 1)*(self.adult_n*100+self.children_n*50)
return p
adult = int(input('成年人数量'))
children = int(input('儿童数量'))
weekday = int(input('是否为周末,输入0或1'))
t = Ticket(adult,children,weekday)
t.price()
---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
<ipython-input-49-53a739506dec> in <module>
----> 1 adult = int(input('成年人数量'))
2 children = int(input('儿童数量'))
3 weekday = int(input('是否为周末,输入0或1'))
4 t = Ticket(adult,children,weekday)
5 t.price()
c:\users\c peg\appdata\local\programs\python\python37\lib\site-packages\ipykernel\kernelbase.py in raw_input(self, prompt)
861 self._parent_ident,
862 self._parent_header,
--> 863 password=False,
864 )
865
c:\users\c peg\appdata\local\programs\python\python37\lib\site-packages\ipykernel\kernelbase.py in _input_request(self, prompt, ident, parent, password)
902 except KeyboardInterrupt:
903 # re-raise KeyboardInterrupt, to truncate traceback
--> 904 raise KeyboardInterrupt("Interrupted by user") from None
905 except Exception as e:
906 self.log.warning("Invalid Message:", exc_info=True)
KeyboardInterrupt: Interrupted by user
# 类定义
class people:
# 定义基本属性
name = ''
age = 0
# 定义私有属性,私有属性在类外部无法直接进行访问
__weight = 0
# 定义构造方法
def __init__(self, n, a, w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s 说: 我 %d 岁。" % (self.name, self.age))
# 单继承示例
class student(people):
grade = ''
def __init__(self, n, a, w, g):
# 调用父类的构函
people.__init__(self, n, a, w)
self.grade = g
# 覆写父类的方法
def speak(self):
print("%s 说: 我 %d 岁了,我在读 %d 年级" % (self.name, self.age, self.grade))
s = student('小马的程序人生', 10, 60, 3)
s.speak()
小马的程序人生 说: 我 10 岁了,我在读 3 年级
魔法方法
能够让对象拥有更多的操作
class Cat():
'''这是说明'''
def __init__(self,name,age,color):
self.name = name
self.age = age
self.color = color
print(f"i am a cat,my name is {self.name},i am {self.age} and {self.color}")
def __del__(self):
print('i am dead')
def __call__(self,*ar):
print(ar[0]+ar[1])
def __str__(self):
return 'i am a cat,my name is %s'%self.name
def __len__(self):
return self.age
def __add__(self,other):
return f'很多猫,总长为{self.age}+{other.age}'
__init__
实例被创建时自动调用
cat = Cat('mimi',5,'black')
i am a cat,my name is mimi,i am 5 and black
__del__
对象被删除时自动调用
del cat
i am dead
doc ,module,calss
描述,所属的模块,所属的类
cat.__doc__,cat.__module__,cat.__class__
('这是说明', '__main__', __main__.Cat)
call
让对象像函数一样可以被调用
cat(1,2)
3
dict
查看属性
cat.__dict__
{'name': 'mimi', 'age': 5, 'color': 'black'}
str
在print(cat)时得到指定信息,否则结果为<main.Cat at 0x14aa5a876d8>
print(cat),cat
i am a cat,my name is mimi
(None, <__main__.Cat at 0x14aa5a876d8>)
len
当存在__len__是,可以使用len函数
len(cat)
5
add
cat1 = Cat('xiaohong',4,'w')
cat2 = Cat('x',7,'h')
cat1 + cat2
i am a cat,my name is xiaohong,i am 4 and w
i am a cat,my name is x,i am 7 and h
'很多猫,总长为4+7'