Python | 类和对象(Python | classes and objects)

一、类与对像的创建1. 类的组成类属性、实例方法、静态方法、类方法

Class Student:
    pass

Student为类的名称,每个单词的首字母大写,其余小写

直接写在类里的变量,称为类属性

实例方法

def eat(self):
    print("吃")

静态方法

@staticmethoddef method():
    print("staticmethod进行修饰为静态方法,不能使用self")

在类之外定义的称之为函数,在类之内定义的称之为方法静态方法进行修饰,不能使用self

类方法

@classmethoddef cm(cls):
    print("classmethod进行修饰为类方法,使用cls")

init初始化方法

def __init__(self,name,age):
    self.name = name
    self.age = age

self.name称为实体属性,进行了一个赋值操作,将局部变量的name的值赋给实体变量

2. 对象的创建对象的创建又称为类的实例化语法:实例名 = 类名()意义:有了实例,就可以调用类中的内容

总结类属性:类中方法外的变量称之为类属性,被该类的所有对象所共享类方法:使用@classmethod修饰的方法,使用类名直接访问的方法静态方法:使用@staticmethod修饰的方法,使用类名直接访问的方法

Student.native_pace # 访问类属性Student.cm() # 调用类方法Student.sm() # 调用静态方法

class Student:
    native_pace='安徽'
    @classmethod
    def cm(cls):
        print("classmethod进行修饰为类方法,使用cls")
    @staticmethod
    def method():
        print("staticmethod进行修饰为静态方法,不能使用self")
print(Student.native_pace)
Student.cm()
Student.method()           

面向对象的三大属性

封装:提高程序的安全性继承:提高代码的复用性多态:提高代码的可扩展性和可维护性

1.封装 封装:提高程序的安全性 将数据(属性)和行为(方法)包装到类对象中。在方法内部对属性进行操作,在类对象的外部调用方法。这样,无需关心方法内部的具体实现细节,从而隔离了复杂度 在python中没有专门的修饰符用于属性的私有,如果该属性不需要在类对象外部被访问,前面使用两个“_”

class Student:
    def __init__(self,name,age):
        self.name=name
        self.__age=age
    def show(self):
        print(self.name,self.__age)
stu=Student("张三",20)
stu.show()
# print(stu.name)
#print(dir())
# print(stu._Student__age)

年龄不希望在类的外部被调用,所以使用两个“_”在类的外部可以通过_student__age进行访问

2.继承 语法格式: class 字典类名(父级1,父级2): 如果一个类都没有继承任何类,则默认继承object

class Person(object):
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def info(self):
        print(self.name,self.age)
class Student(Person):
    def __init__(self,name,age,stu_no):
        super().__init__(name,age)
        self.stu_no=stu_no
class Teacher(Person):
    def __init__(self,name,age,teachofyear):
        super().__init__(name,age)
        self.teachofyear=teachofyear
stu=Student("张三",20,"1001")
teacher=Teacher("李四",34,10)
stu.info()
teacher.info()
打印结果:
张三 20
李四 34

多继承

class A(object):
    pass
class B(object):
    pass
class C(A,B):
    pass

3.方法重写 如果子类对继承父类的某个属性或方法不满意,可以在子类中对其(方法体)进行重新编写 子类重写后的方法中可以通过super().xxx()调用父类中被重写的方法

class Person(object):
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def info(self):
        print(self.name,self.age)

class Student(Person): #继承
    def __init__(self,name,age,stu_no):
        super().__init__(name,age)
        self.stu_no=stu_no
    def info(self):
        super().info()
        print("学号",self.stu_no)

class Teacher(Person):
    def __init__(self,name,age,teachofyear):
        super().__init__(name,age)
        self.teachofyear=teachofyear
    def info(self):
        super().info()
        print("教龄:",self.teachofyear)
stu=Student("张三",20,"1001")
teacher=Teacher("李四",34,10)
stu.info()
print("-------")
teacher.info()打印结果:张三 20学号 1001-------李四 34教龄: 10

4.object类 object类是所有类的父类,因此所有类都有object类的属性和方法; 内置函数dir()可查看指定对象所有属性; object有一个__str__()方法,用于返回一个对于“对象的描述”,对应于内置函数str(), 经常用于print()方法,帮我们查看对象的信息,所以我们经常会对__str__()进行重写

class Student:
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def __str__(self):
        return "我的名字是{0},今年{1}岁".format(self.name,self.age)
stu=Student("张三",20)
print(dir(stu))
print(stu)
print(type(stu))打印结果:['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name']我的名字是张三,今年20岁<class '__main__.Student'>

5.多态

https://blog.csdn.net/m0_64118193/article/details/124612710

————————

1、 Class and object creation 1 Class composition, class attribute, instance method, static method, class method

Class Student:
    pass

Student is the name of the class. The first letter of each word is uppercase and the rest is lowercase

Variables written directly in a class are called class attributes

Example method

def eat(self):
    print("吃")

Static method

@staticmethoddef method():
    print("staticmethod进行修饰为静态方法,不能使用self")

Functions defined outside the class are called functions, and methods defined inside the class are called methods. Static methods are used for modification. Self cannot be used

Class method

@classmethoddef cm(cls):
    print("classmethod进行修饰为类方法,使用cls")

Init initialization method

def __init__(self,name,age):
    self.name = name
    self.age = age

self. Name is called an entity attribute. It performs an assignment operation to assign the value of the name of the local variable to the entity variable

2. Object creation object creation is also called class instantiation syntax: instance name = class name () meaning: with an instance, you can call the content in the class

Summarize class attributes: variables outside the methods in the class are called class attributes, which are shared by all objects of the class. Class methods: methods decorated with @ classmethod, methods directly accessed with class name. Static methods: methods decorated with @ staticmethod, methods directly accessed with class name

Student. native_ pace # Access class property student cm() # Call class method student sm() # Call static method

class Student:
    native_pace='安徽'
    @classmethod
    def cm(cls):
        print("classmethod进行修饰为类方法,使用cls")
    @staticmethod
    def method():
        print("staticmethod进行修饰为静态方法,不能使用self")
print(Student.native_pace)
Student.cm()
Student.method()           

Three attributes of object-oriented

Encapsulation: improve program security inheritance: improve code reusability polymorphism: improve code scalability and maintainability

1. Packaging Encapsulation: improve program security Wrap data (properties) and behavior (Methods) into class objects. Operate on the attribute inside the method and call the method outside the class object. In this way, there is no need to care about the specific implementation details inside the method, thus isolating the complexity In Python, there is no special modifier for the private of the attribute. If the attribute does not need to be accessed outside the class object, the two “” are used in front

class Student:
    def __init__(self,name,age):
        self.name=name
        self.__age=age
    def show(self):
        print(self.name,self.__age)
stu=Student("张三",20)
stu.show()
# print(stu.name)
#print(dir())
# print(stu._Student__age)

Age doesn’t want to be called outside the class, so use two “” Outside the class, you can_ student__ Age access

2. Succession Syntax format: Class dictionary class name (parent 1, parent 2): If a class does not inherit any classes, it inherits object by default

class Person(object):
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def info(self):
        print(self.name,self.age)
class Student(Person):
    def __init__(self,name,age,stu_no):
        super().__init__(name,age)
        self.stu_no=stu_no
class Teacher(Person):
    def __init__(self,name,age,teachofyear):
        super().__init__(name,age)
        self.teachofyear=teachofyear
stu=Student("张三",20,"1001")
teacher=Teacher("李四",34,10)
stu.info()
teacher.info()
打印结果:
张三 20
李四 34

Multiple inheritance

class A(object):
    pass
class B(object):
    pass
class C(A,B):
    pass

3. Method rewriting If a subclass is not satisfied with a property or method inherited from the parent class, it can be rewritten in the subclass (method body) Subclass overridden methods can be overridden through super() Xxx() calls the overridden method in the parent class

class Person(object):
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def info(self):
        print(self.name,self.age)

class Student(Person): #继承
    def __init__(self,name,age,stu_no):
        super().__init__(name,age)
        self.stu_no=stu_no
    def info(self):
        super().info()
        print("学号",self.stu_no)

class Teacher(Person):
    def __init__(self,name,age,teachofyear):
        super().__init__(name,age)
        self.teachofyear=teachofyear
    def info(self):
        super().info()
        print("教龄:",self.teachofyear)
stu=Student("张三",20,"1001")
teacher=Teacher("李四",34,10)
stu.info()
print("-------")
teacher.info()打印结果:张三 20学号 1001-------李四 34教龄: 10

4. Object class Object class is the parent class of all classes, so all classes have the properties and methods of object class; The built-in function dir() can view all properties of the specified object; Object has a__ str__ () method, which is used to return a description of the “object”, corresponding to the built-in function str (), It is often used in the print () method to help us view the information of the object, so we often__ str__ () Rewrite

class Student:
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def __str__(self):
        return "我的名字是{0},今年{1}岁".format(self.name,self.age)
stu=Student("张三",20)
print(dir(stu))
print(stu)
print(type(stu))打印结果:['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name']我的名字是张三,今年20岁<class '__main__.Student'>

5. Polymorphism

https://blog.csdn.net/m0_64118193/article/details/124612710