Detailed usage of class members and modifiers in Python object-oriented

Posted by iJoseph on Fri, 08 Oct 2021 08:43:56 +0200

Overview of class 1 members

Class members can be divided into three categories: fields, methods, and properties. The main relationships are as follows:

In the members of the above class, common fields are stored in objects; Other members are stored in the class, that is, no matter how many objects are created, the object itself only retains the common fields in the member, and other members are stored in the class.

2 field

Fields are divided into ordinary fields and static fields. Ordinary fields belong to objects and static fields belong to classes; Therefore, their location in memory is also different. Here's how they are defined and accessed:

class Subject(object):

    # Static field
    subject = "the subject of mathematics"

    def __init__(self, name):
        # General field
        self.name = name

# Common fields are accessed through objects
obj = Subject("Advanced mathematics")    
print(obj.name)             # Advanced mathematics

# Static fields are accessed through classes
print(Subject.subject)      # the subject of mathematics

# Accessing static fields through objects (not recommended)
print(obj.subject)          # the subject of mathematics

In fact, each object stores a pointer to its class, pointing to the class. Object through this pointer, you can find the class that created itself. When we write code, we can write fields common to objects as static fields.

3 method

Methods include ordinary methods, static methods and class methods. The three methods belong to classes in memory. The difference lies in different calling methods and different parameters passed in when defining methods.

'''
No one answers the problems encountered in learning? Xiaobian created a Python exchange of learning QQ Group: 531509025
 Look for like-minded friends to help each other,There are also good videos and tutorials in the group PDF e-book!
'''
class Person(object):

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

    # Common method without decorator parameter: self
    def talk(self):
        print("my name is %s" % self.name)

    # Class method decorator: @ classmethod parameter: CLS (representing the class itself)
    @classmethod
    def class_talk(cls):
        print("class Person")

    # Static method decorator: @ staticmethod parameter: None
    @staticmethod
    def static_talk():
        print("static function")

# Call normal methods through objects
obj = Person("Jeo Chen")
obj.talk()               # my name is Jeo Chen

# Calling class methods through classes
Person.class_talk()      # class Person

# Calling static methods through classes
Person.static_talk()     # static function

In Python, class methods and static methods can be called through objects, but it is not recommended:

# Calling class methods through objects (not recommended)
obj.class_talk()         # class Person
# Calling static methods through objects (not recommended)
obj.static_talk()        # static function

Common methods: called by objects; At least one self parameter; When a normal method is executed, the object calling the method is automatically assigned to self;
Class method: called by class; At least one cls parameter; When executing a class method, the class calling the method is automatically assigned to cls;
Static method: called by class; No default parameters;

4 properties

After mastering the common method, the attribute is very simple. Just add a decorator @ property to the ordinary method to convert the ordinary method into a property.

'''
No one answers the problems encountered in learning? Xiaobian created a Python exchange of learning QQ Group: 531509025
 Look for like-minded friends to help each other,There are also good videos and tutorials in the group PDF e-book!
'''
class Person(object):

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

    # The difference between properties and ordinary methods is to add a decorator @ property
    @property
    def talk(self):
        return "my name is %s" % self.name

# Accessing properties through objects
obj = Person("Liu You Yuan")
print(obj.talk)     # my name is Liu You Yuan

From the above, accessing properties is different from accessing common methods:

  • Access properties: object.func
  • Access method: object (. Func)

Property provides a way to access common methods just like normal fields.

If you want to modify the value of a property or delete a property, you should have three functions with the same name in the class, and the decorators on the functions are: @ property, @ method name. setter, @ method name. Delete.

class Salary(object):
    def __init__(self, money):
        # base pay
        self.basic_salary = money
        # Commission
        self.rate = 1.2

    @property
    def salary(self):
        return self.basic_salary * self.rate

    # modify attribute
    @salary.setter
    def salary(self, value):
        self.basic_salary = value

    # Delete attribute
    @salary.deleter
    def salary(self):
        del self.basic_salary

obj = Salary(20000)
print(obj.salary)    # 24000.0 salary method to trigger @ property decoration

obj.salary = 30000
print(obj.salary)    # 36000.0 method to trigger @ salary.setter decoration

del obj.salary       # The salary method that triggers the @ salary. Delete decoration

The above attributes are created in the form of decoration. There is also a special method to create attributes in Python as follows:

class Person(object):

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

    def get_firstname(self):
        return self.name[:3]

    fistname = property(get_firstname)  # Auto return get_ Return value of firstname()

obj = Person("Liu You Yuan")
print(obj.fistname)      # Liu

How to modify and delete attributes in this way?

'''
No one answers the problems encountered in learning? Xiaobian created a Python exchange of learning QQ Group: 531509025
 Look for like-minded friends to help each other,There are also good videos and tutorials in the group PDF e-book!
'''
class Salary(object):
    def __init__(self, money):
        # base pay
        self.basic_salary = money
        # Commission index
        self.rate = 1.2

    def get_salary(self):
        return self.basic_salary * self.rate

    def set_salary(self, value):
        self.basic_salary = value

    def del_salary(self):
        del self.basic_salary

    salary = property(get_salary, set_salary, del_salary, "describe")

obj = Salary(20000.0)
print(obj.salary)

obj.salary = 30000.0
print(obj.salary)

del obj.salary

Modifier for class 5 members

There are two types of members in a class, public members and private members.
Public members, accessible anywhere.
Private members, methods can only be used inside a class. Put two underscores before the names of ordinary members. If there are static fields:__ name = "Mathematics"

PS: you can use objects_ Class name__ Private members to force access to private members, but not recommended.

class Person:

    Country = "China"
    __P = "SC"

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

    def __hello(self):
        print("[{}] age is [{}]".format(self.name, self.__age))

    def hi(self):
        self.__hello()

obj = Person("Liu You Yuan", 23)
print(obj.name)      # Access public members

# print(Person.__P)  # An error is reported and the external cannot be accessed
# print(obj.__age)   # An error is reported and the external cannot be accessed

# Mandatory access can
print(obj._Person__age)    # 23

obj.hi()    # [Liu You Yuan] age is [23]

Topics: Python OOP