class Student:
name = None
gender = None
nationality = None
native_place = None
age = None
def say_hi(self):
print(self.name)
def dowork(self,work):
print(f"{self.name} {work}")
student1 = Student()
student1.name = "xxx"
student1.gender = "男"
student1.nationality = "中国"
student1.native_place = "山东省"
student1.age = 31
print(student1.name)
student1.dowork("codding")
student1.say_hi()
#构造方法
class Animal:
name = None
age = None
def __init__(self,name,age):
self.name = name
self.age = age
print("animal init")
dog = Animal(name="dog",age=11)
#构造方法
class Animal:
name = None
age = None
def __init__(self,name,age):
self.name = name
self.age = age
print("animal init")
# 输出打印
def __str__(self) -> str:
return f"{self.name} age={self.age}"
#比较 小于 大于
def __lt__(self, other):
return self.age < other.age
#小于等于
def __le__(self, other):
return self.age <= other.age
#等于 ==
def __eq__(self, __value: object) -> bool:
return self.age == other.age
dog = Animal(name="dog",age=11)
print(dog)
dog2 = Animal(name="dog2",age=12)
print(dog > dog2)
私有成员变量变量名以__(双下划线开头)
私有成员方法方法名以__(双下划线开始)
class Phone:
#私有成员变量
__current_voltage = 0
#私有成员函数
def __keep_single_core(self):
print("single")
def callby_5g(self):
if self.__current_voltage >= 1:
print("__current_voltage >= 1")
else:
self.__keep_single_core()
print("__current_voltage < 1")
phoe = Phone()
phoe.callby_5g()
#构造方法
class Animal:
name = None
age = None
def __init__(self,name,age):
self.name = name
self.age = age
print("animal init")
# 输出打印
def __str__(self) -> str:
return f"{self.name} age={self.age}"
#比较 小于 大于
def __lt__(self, other):
return self.age < other.age
#小于等于
def __le__(self, other):
return self.age <= other.age
#等于 ==
def __eq__(self, __value: object) -> bool:
return self.age == other.age
dog = Animal(name="dog",age=11)
print(dog)
dog2 = Animal(name="dog2",age=12)
print(dog > dog2)
class Cat(Animal):
kind = None
def color(self):
print("white_yellow")
cat1 = Cat(name="波斯猫",age=11)
cat1.kind = "xxxxx"
cat1.color()
统一行为不同对象的不同表现形式