Python--class (explain)

Python class

1. Object-oriented:

Creating an object from a class is called instantiation, which allows you to use an instance of the class.

Object-oriented programming (OOP for short) is a method of encapsulating code.

Code encapsulation, in fact, is to hide the specific code that implements the function, leaving only the interface for the user to use, just like using a computer, the user only needs to use the keyboard and mouse to realize some functions, and does not need to know how it works internally.

In Python, all variables are actually objects, including integers (int), floating point (float), strings (str), lists (list), tuples (tuple), dictionaries (dict) and sets ( set).

In object-oriented, common terms include:

  • **Class: It can be understood as a template through which countless specific instances can be created. **For example, the tortoise written earlier represents only the species of tortoise, through which countless instances can be created to represent tortoises with various characteristics (this process is also called class instantiation).
  • **Object: The class cannot be used directly, only the instance (also known as object) created through the class can be used. **This is a bit like the relationship between car drawings and cars. The drawings themselves (classes) cannot be used by people, but a car (object) created through drawings can be used.
  • **Attributes: All variables in a class are called attributes. **For example, in the tortoise class, bodyColor, footNum, weight, and hasShell are all attributes owned by this class.
  • **Methods: All functions in a class are usually called methods. **However, unlike functions, class methods must contain at least one self parameter (will be described in detail later). For example, in the tortoise class, crawl(), eat(), sleep(), and protect() are all methods owned by this class. Class methods cannot be used alone, but can only be used together with objects of the class.

2. Define the class:

Class order of use:

  • Create (define) a class.
  • Create an instance object of the class, and implement specific functions through the instance object.

grammar:

class 类名:
    多个(≥0)类属性...
    多个(≥0)类方法...

Note: Neither class attributes nor class methods are necessary, and the positions of class attributes and class methods are arbitrary, and there is no fixed order. But generally attributes come first and methods follow.

class TheFirstDemo():
    """ 第一个python类 """
    # 定义类属性:
    name = "萧楚河"

    # 定义say类方法:
    def say(self, content):
        print(content)

Note: The attributes defined in the class are called class attributes, and the attributes defined in the class method are called instance attributes.

3. _ _ init _ _() class construction method:

The constructor is used when creating an object, and it is automatically called by the Python interpreter whenever an instance object of a class is created.

grammar:

def __init__(self,...):
    代码块
class TheFirstDemo():
    """ 第一个python类 """
    # 定义类属性:
    name = "萧楚河"

    # 定义构造方法:
    def __init__(self):
        print("调用构造方法")

    # 定义say类方法:
    def say(self, content):
        print(content)

4. Create and use classes:

class initDemo():
    """ 构造方法练习 """
    name = 'jack'

    # 构造方法:
    def __init__(self, school, age):
        print(f"学校名字是:{
      
      school}, 今年{
      
      age}岁了。")

    # 定义say 方法
    def say(self):
        print("我是say 方法。")

pp2 = initDemo("师范附中", 21)  # 学校名字是:师范附中, 今年21岁了。
pp2.say()  # 我是say 方法。

When an object is created, the __init()__ method is implicitly called. And the self inside does not need to pass parameters.

The defined class can only be used after instantiation, that is, after the object is created using the class.

  • Access or modify the instance variables of the class object, and even add new instance variables or delete existing instance variables;

  • Calling methods of class objects, including calling existing methods and dynamically adding methods to class objects.

# 类的使用
class Cstady():
    """ 类对象的使用 """
    name = 'tom'
    age = 21

    # say 方法:
    def say(self, content):
        print(content)

cc = Cstady()
print(f"姓名为:{
      
      cc.name}, 年龄:{
      
      cc.age}")  # 姓名为:tom, 年龄:21
cc.say("我怎么这么帅")   # 我怎么这么帅

cc.name = '萧楚河'
print(cc.name)   # 萧楚河

cc.email = '[email protected]'
print(cc.email)   # [email protected]  # 给类对象动态添加 变量。

# 动态删除实例变量:
del cc.email
print(cc.email)  # AttributeError: 'Cstady' object has no attribute 'email'

5. Usage of self:

Whether explicitly creating a class constructor or adding an instance method to a class, the self parameter is required as the first parameter of the method.

Python only stipulates that whether it is a construction method or an instance method, it must contain at least one parameter, and does not specify the specific name of the parameter. The reason why it is named self is just a custom among programmers. Obeying this convention can make the code we write more readable.

Through the self parameter, it is equivalent to the door key of each house, which can ensure that the owner of each house can only enter his own house (each class object can only call its own class variables and class methods).

The same class can generate multiple objects. When an object calls a class method, the object will automatically pass its own reference as the first parameter to the method. In other words, Python will automatically bind the first parameter of the class The parameter points to the object on which the method is invoked .

# self 的使用
class Slee():
    """ self详解 """
    def __init__(self):
        print("调用构造函数")

    def say(self):
        print(self, "学习self的作用。")

lili = Slee()
lili.say()    # <__main__.Slee object at 0x000002049B8466B0> 学习self的作用。

xiaom = Slee()
xiaom.say()   # <__main__.Slee object at 0x000002049B846650> 学习self的作用。

For the self parameter in the constructor, it represents the class object currently being initialized.

class Person():
    """ 定义一个person类 """
    name = "xxxx"

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

pp = Person('tom猫')
print(pp.name)   # tom猫

6. Class variables and instance variables:

  • In the class body, outside all functions: variables defined in this scope are called class attributes or class variables ;

  • In the class body, inside all functions: variables defined in the form of " self. variable name " are called instance attributes or instance variables ;

  • In the class body, inside all functions: Variables defined in the form of " variable name = variable value " are called local variables .

Unlike class variables, modifying the value of an instance variable through an object will not affect other instantiated objects of the class, let alone class variables with the same name.

class Person():
    """ person类 """
    name = '小明'
    url = 'www.baidu.com'

    def __init__(self):
        self.name = 'linux'
        self.url = 'hello,linux'

    def say(self):
        self.age = 13
# 实例对象1
p01 = Person()
p01.name = 'java'
p01.url = 'java is very good.'
print(p01.name , p01.url)
# 实例对象2
p02 = Person()
print(p02.name, p02.url)
# 类变量
print(Person.name)
print(Person.url)

Python only supports adding instance variables for specific objects.

Usually, local variables are defined for the realization of the function of the class method. One thing to note is that local variables can only be used in the function where they are located. After the function is executed, the local variables will also be destroyed.

class Sum():
    """ 求和类 """
    def sum(self, num):
        s = 0.8 * num
        print(f"价格为:{
      
      s}")

ss = Sum()
ss.sum(10)  # 8

7. Instance methods, static methods and class methods:

The method modified with @classmethod is a class method; the method modified with @staticmethod is a static method; the method without any modification is an instance method.

A constructor is also an instance method.

Among them @classmethod and @staticmethod are both function decorators.

  • Instance method:
class Person():
    """ 实例方法 """
    def __init__(self):
        print("构造方法。")

    def say(self):
        print("实例方法。")
pp = Person()
pp.say()
  • class method:
class Person():
    """ 实例方法 """
    def __init__(self):
        print("构造方法。")

    # 实例方法
    def say(self):
        print("实例方法。")

    # 类方法
    @classmethod
    def info(cls):
        print("正在调用类方法。")

pp = Person()
pp.say()
pp.info()
Person.info()  # 正在调用类方法。(推荐)

It is recommended to use the class name to call the class method directly, of course, it can also use the instance object to call (not recommended).

  • static method:

Static methods are actually the functions we have learned. The only difference from functions is that static methods are defined in the space of the class, while functions are defined in the space where the program is located.

A static method has no special parameters like self, cls, so the Python interpreter will not do any class or object binding for the parameters it contains. Because of this, any class attributes and class methods cannot be called in the static methods of the class.

# 静态方法:
    @staticmethod
    def show(name, age):
        print(f"姓名是:{
      
      name},年龄是:{
      
      age}")
        
Person.show('小明', 21)  # 姓名是:小明,年龄是:21
pp.show('小红', 19)  # 姓名是:小红,年龄是:19

The method of accessing class members with an instance object of the class is called a bound method, while the method of calling a class member with a class name is called an unbound method.

8. Class special method:

1. repr () method: display attributes:

Typically, an instantiated object is output directly.

class CLanguage:
    pass
clangs = CLanguage()
print(clangs)  # <__main__.CLanguage object at 0x000001A7275221D0>

If you want to output the basic information of the object, such as what attributes the object has, what are their values, and so on.

class CLanguage:
    def __init__(self):
        self.name = "C语言中文网"
        self.add = "http://c.biancheng.net"
    def __repr__(self):
        return "CLanguage[name="+ self.name +",add=" + self.add +"]"
clangs = CLanguage()
print(clangs)   # CLanguage[name=C语言中文网,add=http://c.biancheng.net]

The repr () method is the method used by the instantiated object of the class to "introduce itself". By default, it will return the "class name + object at + memory address" of the current object, and if this method is rewritten, you can Make a custom self-describing message for it.

2. del () method: destroy the object:

If the previously created class instantiation object is no longer used later, it is best to manually destroy it in an appropriate place to release the memory space it occupies (the whole process is called garbage collection (GC for short)).

In most cases, Python developers do not need to manually perform garbage collection, because Python has an automatic garbage collection mechanism (described below), which can automatically destroy unused instance objects.

class CLanguage:
    def __init__(self):
        print("调用 __init__() 方法构造对象")
    def __del__(self):
        print("调用__del__() 销毁对象,释放其空间")
clangs = CLanguage()
del clangs

3. dir () usage: list all attribute (method) names of the object:

The dir() function can list all the property names and method names owned by an object, and this function will return an ordered list containing all property names and method names.

# __dir__()方法的用法
class Person:
    def __init__ (self,):
        self.name = "C语言中文网"
        self.add = "http://c.biancheng.net"
    def say(self):
        pass
    
pp = Person()
print(dir(pp))

['__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__', 'add', 'name', 'say']

Note: The dir() function not only outputs the newly added attribute names and methods (the last 3) in this class, but also outputs the attribute names and method names inherited from the parent class (here, the object class).

The internal implementation of the dir() function actually sorts the attribute names and method names returned by the method on the basis of calling the dir () method of the parameter object.

4. __dict__ attribute: View the dictionary composed of all attribute names and attribute values ​​inside the object:

# __dict__()方法
class Person():
    a = 1
    b = 2
    def __init__(self):
        self.name = '萧楚河'
        self.age = 21
print(Person.__dict__)

pp = Person()
print(pp.__dict__)

{
    
    '__module__': '__main__', 'a': 1, 'b': 2, '__init__': <function Person.__init__ at 0x000001E501CFA710>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
{
    
    'name': '萧楚河', 'age': 21}

For the parent class and subclass with inheritance relationship, the parent class has its own dict , and the subclass also has its own dict , which will not contain the dict of the parent class .

With the help of the dictionary obtained by calling the dict attribute of the class instance object , you can use the dictionary to modify the value of the instance attribute .

Note that the value of a class variable cannot be modified in a similar manner.

5. setattr(), getattr(), hasattr() functions:

1. hasattr() function

Used to determine whether a class instance object contains a property or method with a specified name.

hasattr(obj, name)

Among them, obj refers to the instance object of a certain class, and name represents the specified attribute name or method name. At the same time, the function will feed back the result of the judgment (True or False) as a return value.

# hasattr()函数
class Person():
    def __init__(self):
        self.name = "jack"
        self.add = "www.baidu.com"

    def say(self):
        print("我正在学Python。")
pp = Person()
print(hasattr(pp, "name"))  # True
print(hasattr(pp, "add"))   # True
print(hasattr(pp, "say"))   # True

We can only use this function to judge whether the instance object contains the attribute or method of the name, but we cannot accurately judge whether the name represents the attribute or the method.

2. getattr() function:

The getattr() function gets the value of a specified attribute in a class instance object.

getattr(obj, name[, default])

obj represents the specified class instance object, name represents the specified attribute name, and default is an optional parameter, which is used to set the default return value of the function, that is, when the function search fails, if the default parameter is not specified, the program will directly AttributeError will be reported, otherwise the function will return the value specified by default.

class Person():
    def __init__(self):
        self.name = "jack"
        self.add = "www.baidu.com"

    def say(self):
        print("我正在学Python。")
pp = Person()
print(getattr(pp, "name"))  # jack
print(getattr(pp, "add"))   # www.baidu.com
print(getattr(pp, "say"))   # <bound method Person.say of <__main__.Person object at 0x0000021581FD75E0>>
print(getattr(pp, "show", 'noshow'))   # noshow

3. setattr() function:

The function of the setattr() function is relatively complicated, and its most basic function is to modify the attribute value in the class instance object. Secondly, it can also dynamically add properties or methods to instance objects.

setattr(obj, name, value)
class Person():
    def __init__(self):
        self.name = "jack"
        self.add = "www.baidu.com"

    def say(self):
        print("我正在学Python。")
pp = Person()
print(pp.name)  # jack
print(pp.add)  # www.baidu.com
setattr(pp, "name", "tom")
setattr(pp, "add", "hello,python.")
print(pp.name)  # tom
print(pp.add)   # hello,python.

The setattr() function can also modify a class attribute into a class method, and it can also modify a class method into a class attribute.

def say(self):
    print("我正在学Python")
class CLanguage:
    def __init__ (self):
        self.name = "hello"
        self.add = "china"
clangs = CLanguage()
print(clangs.name)  # hello
print(clangs.add)   # china
setattr(clangs,"name",say)
clangs.name(clangs)   # 我正在学Python

When using the setattr() function to modify the attribute or method of the execution name in the instance object, if the name lookup fails, the Python interpreter will not report an error, but will dynamically add an attribute or method with the specified name to the instance object.

9. Check type: (issubclass, isinstance)

  • issubclass(cls, class_or_tuple): Checks whether cls is a subclass of any of the classes contained in the latter class or tuple.
  • isinstance(obj, class_or_tuple): Checks whether obj is an object of any of the classes contained in the latter class or tuple.
# 定义一个字符串
hello = "Hello"
# "Hello"是str类的实例,输出True
print('"Hello"是否是str类的实例: ', isinstance(hello, str))

# "Hello"是object类的子类的实例,输出True
print('"Hello"是否是object类的实例: ', isinstance(hello, object))

# str是object类的子类,输出True
print('str是否是object类的子类: ', issubclass(str, object))

# "Hello"不是tuple类及其子类的实例,输出False
print('"Hello"是否是tuple类的实例: ', isinstance(hello, tuple))

# str不是tuple类的子类,输出False
print('str是否是tuple类的子类: ', issubclass(str, tuple))

# 定义一个列表
my_list = [2, 4]
# [2, 4]是list类的实例,输出True
print('[2, 4]是否是list类的实例: ', isinstance(my_list, list))

# [2, 4]是object类的子类的实例,输出True
print('[2, 4]是否是object类及其子类的实例: ', isinstance(my_list, object))

# list是object类的子类,输出True
print('list是否是object类的子类: ', issubclass(list, object))

# [2, 4]不是tuple类及其子类的实例,输出False
print('[2, 4]是否是tuple类及其子类的实例: ', isinstance([2, 4], tuple))

# list不是tuple类的子类,输出False
print('list是否是tuple类的子类: ', issubclass(list, tuple))

Both issubclass() and isinstance() functions can take a tuple as the second argument.

# str是list或tuple或object的子类,输出True
print('str是否为list或tuple或object的子类 ', issubclass(str, (list, tuple, object)))
  • Python provides a bases attribute for all classes, through which you can view all direct parent classes of the class, which returns a tuple of all direct parent classes.
  • Python also provides a subclasses () method for all classes, through which you can view all the direct subclasses of the class, which returns a list of all subclasses of the class.

10. call () method:

The function of the call () method is similar to overloading the () operator in the class, so that the class instance object can be used in the form of "object name ()" just like calling a normal function.

class CLanguage:
    # 定义__call__方法
    def __call__(self,name,add):
        print("调用__call__()方法",name,add)
clangs = CLanguage()
clangs("hello","china")   # 调用__call__()方法 hello china

Use call () to make up for the shortcomings of the hasattr() function:

class CLanguage:
    def __init__ (self):
        self.name = "张三"
        self.add = "china"
    def say(self):
        print("我正在学Python")
clangs = CLanguage()
if hasattr(clangs,"name"):
    print(hasattr(clangs.name,"__call__"))   # False
print("**********")
if hasattr(clangs,"say"):
    print(hasattr(clangs.say,"__call__"))   # True

11. Operator overloading:

Overloading an operator refers to defining and implementing a processing method corresponding to the operator in the class, so that when the class object is performing an operator operation, the system will call the corresponding method in the class to process it.

class MyClass: #自定义一个类
    def __init__(self, name , age): #定义该类的初始化函数
        self.name = name #将传入的参数值赋值给成员交量
        self.age = age
    def __str__(self): #用于将值转化为字符串形式,等同于 str(obj)
        return "name:"+self.name+";age:"+str(self.age)
   
    __repr__ = __str__ #转化为供解释器读取的形式
   
    def __lt__(self, record): #重载 self<record 运算符
        if self.age < record.age:
            return True
        else:
            return False
   
    def __add__(self, record): #重载 + 号运算符
        return MyClass(self.name, self.age+record.age)
myc = MyClass("Anna", 42) #实例化一个对象 Anna,并为其初始化
mycl = MyClass("Gary", 23) #实例化一个对象 Gary,并为其初始化
print(repr(myc)) #name:Anna;age:42
print(myc) #name:Anna;age:42
print (str (myc)) #格式化对象 myc ,输出"name:Anna;age:42"
print(myc < mycl) #比较 myc<mycl 的结果,输出 False
print (myc+mycl) #进行两个 MyClass 对象的相加运算,输出 "name:Anna;age:65"

12. Iterators:

An iterator refers to a container that supports iteration. More precisely, it is a container class object that supports iteration. The container here can be a basic container provided by Python such as a list or a tuple , or a custom container class object. As long as the container supports iteration.

If you want to customize an iterator, you must implement the following two methods in the class:

  • next (self): Returns the next element of the container.

  • iter (self): This method returns an iterator.

Builder:

# 生成器
def intNum():
    print("开始执行。。。")
    for i in range(5):
        yield i
        print("继续执行")
num = intNum()
for i in num:
    print(i)

Compared with iterators, the most obvious advantage of generators is to save memory space, that is, it will not generate all the data at once, but when it is needed and when it is generated.

Guess you like

Origin blog.csdn.net/weixin_53060366/article/details/129932518