kind
Constructor
# 创建类
class Student:
name = None # 成员属性
age = None # 成员属性
def say(self): # 成员方法
print(self.name)
# 构造函数
def __init__(self,name,age):
self.name = name
self.age = age
#创建类对象
my_student= Student()
# 对象的属性 赋值
my_student.name = 'ZEN'
my_student.age = 20
# 获取对象的信息
my_student.say()
# 自动执行构造函数__init__,给属性初始化
my_student1 = Stuendt('Ares-Wang',200)
magic method
There are built-in methods in classes in python, and these built-in methods become magic methods
The magic method is as follows [commonly used]:
- The init constructor is automatically executed
- str string method
- lt less than, greater than sign comparison
- le less than or equal to, greater than or equal to sign comparison
- eq == equal sign
Object Oriented Features
- encapsulation
- polymorphism
- inherit
##Private attributes and private methods in python are the same as C# private member access control. Private
instance objects cannot be accessed, but these private members can be placed inside the class
inherit
class classA:
# classB类 继承classA类 单继承
class classB(classA):
# 多继承 同名的成员属性、成员方法,按继承的顺序,左边的优先级高
# pass 占位符,保证语法完整,让语法不报错,表示无内容,空
class 类名(父类1,父类2,父类3,.....父类N):
pass
Rewriting has the same effect as C# override {override rewrites the virtual of the parent class}, but it is more convenient to understand than C#
class Father:
name = "父类"
def say(self):
return "我是父类"
class Sub(Father):
# name = "子类"
def say(self):
print(super().say())
# print(Father.say(self)) 通过父类.方法(self) 调用父类方法
# print(super().name) 如果Sub类的name 不注释掉,注释掉,都调用父类的name 属性 打印 父类
# print(Father.name) 如果Sub类的name 不注释掉,注释掉,都调用父类的name 属性 打印 父类
# print(self.name) 如果Sub类的name,不注释 则调用Sub的name 打印 子类
return "我是子类"
my_sub = Sub()
print(my_sub.name) # 因Sub类 注释了 name = "子类", 所以此处打印 父类,如果取消注释,则打印 子类
print(my_sub.say())# 调用Sub类的say方法, 因方法通过super().say() 调用父类的say方法,所以打印 我是父类 我是子类
type annotation
Add the type annotation of the variable: type
Grammar format: variable: type
annotation of basic data type
var_1: int = 10 var_1 = 10 without annotation
var_2: float = 3.1415926 var_2 = 3.1415926
var_3: bool = True
var_4: str = 'ZEN'
var_5: list = [1,2,3]
var_6: set = {1,2,3}
var_7: dict = {"key": xx}
var_8: tuple = (1,2,4)
class Person:
pass
per : Person= Person()
generally cannot be seen directly at a glance, so it is annotated
# 函数和方法的形参类型注解语法
def 函数名(形参名称: 类型, 形参名称: 类型,....)-> 返回值类型:
pass
def add(x: int ,y: int) -> 返回值类型:
return x+y
Union type
var_2:list[Union[int,str,list]] =[1,"AA",[3.4]]
polymorphism