一、注意:
在Python中 True
属于int
是不是有点让你感到惊讶?True 也是布尔值(类 bool)。实际上,所有布尔值也是 int。
二、Python 中定义类的要点:
- 类初始化的特殊方法:
__init__(self)
类初始化方法,记住也必须传入 self 的行参,内部调用父类的初始化方法使用super
,在该类的对象被创建时被调用 - 定义类级别的变量
所有的实例对象共享该变量,一个对象改变变量的值,其他的对象中该变量的值也跟着被改变 - 定义对象级别的变量
每个实例对象单独持有的变量。不会随其他实例对象的改变而改变。 - 对象继承父类
class Husky(Dog):
class Dog:
dog_tag = "Dog has 4 legs!" # 定义成员变量(类级别的变量)
# __init__ 类初始化的特殊方法,该类的对象被构建时将调用该方法
def __init__(self, name):
self.name = name # 定义实例变量(实例对象级别的变量)
self.count_woof = 0
def count(self):
self.count_woof += 1
self.speak()
def speak(self):
print("Woof!" * self.count_woof)
def eat(self,food):
if food == "food":
print('Yummy food!')
else:
print('That\'s not food!')
def learn_name(self,name):
self.name = name # 定义实例变量(实例对象级别的变量)
def hear(self,words):
if self.name in words:
self.speak()
class Husky(Dog):
origin = 'We are dogs the name is Husky'
def speak(self):
print('My name is Husky!' * self.count_woof)
class Cat:
def speak(self):
print('Meow!')
三、类和实例的关系判断
type("str")
获取对应的类类型 。isinstance(A, B)
A对象是不是B类型的实例。
例如:
isinstance(True, int) 是 True, 换句话说,布尔值 True 和 False 也是 int 类的成员。True 和 False 是 bool 类的成员,但是 bool 是 int 的子类。issubclass(A, B)
A类是不是B类的子类。
例如:
issubclass(bool, int) 结果是 True
四、什么也不执行的方法 pass
有时候,在定义类时,你希望创建占位符方法,即什么也不执行的方法,但是可以在子类里被替换。Python 有一个特殊的什么也不执行语句,叫做 pass,非常适合这种情况。pass 可以用在类或方法定义里,表示意在什么也不做
class Dog:
def do_trick(self):
pass
class Chihuahua(Dog):
pass
class TrainedChihuahua(Chihuahua):
def do_trick(self):
print("The chihuahua spins in the air and turns briefly into a chicken.")
为何需要这种类/方法?因为在 Python 里不能有不包含任何语句的函数或类。通过在 Dog 类里定义 do_trick,我们能够对任何 Dog 调用该方法,虽然只有 TrainedChihuahua 实例会在调用该方法时执行操作:
>>> fido = Dog()
>>> fido.do_trick()
>>> pupper = TrainedChihuahua()
>>> pupper.do_trick()
The chihuahua spins in the air and turns briefly into a chicken.
五、使用 super()
import turtle
class RedTurtle(turtle.Turtle):
def __init__(self):
super().__init__() # super()返回父类的 self 副本,调用父类的 __init__()方法
self.color('red')
if __name__ == '__main__':
print('redturtle __main__')
不添加super().__init__()
调用父类的初始化方法,将会报下方错误:
Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# File "/Users/guolipeng/Python/PythonDemo/redturtle.py", line 5, in __init__
# self.color('red')
# File "//anaconda3/lib/python3.7/turtle.py", line 2216, in color
# pcolor = self._colorstr(pcolor)
# File "//anaconda3/lib/python3.7/turtle.py", line 2696, in _colorstr
# return self.screen._colorstr(args)
# AttributeError: 'RedTurtle' object has no attribute 'screen'
六、番外篇
Python中的 BIF
Python中的BIF
就是Built-in Functions
,即内置函数的意思,内置函数就是为了方便程序员快速的编写脚本程序。