python 基础 面向对象

2024-01-10 11:29:00

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()

多继承

复写父类方法或变量

类型注解

多态

统一行为不同对象的不同表现形式

文章来源:https://blog.csdn.net/weixin_38432324/article/details/135494983
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。