python Basic Programming - Classes and Examples

Keywords: Python Attribute Programming

Before you understand classes and instances, you need to understand what is object-oriented and what is process-oriented. Procedure-oriented is a process-centric step-by-step operation (call each other, similar to pipeline thinking); object-oriented is a thing-centric, one thing can have its own multiple behaviors, and another thing can have its own multiple behaviors.

Object-oriented basis:

Object: There is no specific thing, it can only be said that everything is an object. For example, people, cars, countries,....

Attributes and Behaviors of an Object: What are the characteristics of the Object or how it behaves? If a person has attributes such as height, hair color and so on, he has behaviors such as sleeping and eating.

Class: Objects with the same attributes and behaviors are abstracted and encapsulated into a class that can describe multiple objects. So classes are abstractions of objects and objects are instances of classes.

Message and Method: Communication between objects is abbreviated as message, and method is to achieve a significant effect of message delivery.

Inheritance: An object is generated by another object or can be abstracted as a class is generated by another class, which can have all the attributes and behaviors of another object.

Polymorphism: The same behavior of multiple objects produces different results

Object-oriented features:

From the above, we can summarize four characteristics: abstraction, encapsulation, inheritance and polymorphism.

The main content of this blog is to simply describe the four features and the basic knowledge of object-oriented, which will expand some knowledge in the process of narration.

Abstraction

Class is the abstraction of business-related things with common characteristics in software development process. So classes are the main form of abstraction in programming languages.

We can abstract "human" into Person class, because human has some common characteristics, we can also abstract "animal" into Animal class.

# Person class
class Person:
    """
    //Human Common Characteristics and Behaviors
    """
    def __init__(self, high, weight):
        self.high = high
        self.weight = weight

    # speak
    def speak(self):
        pass

    # Sleep?
    def sleep(self):
        pass

The code blogger only writes about the common attributes and behaviors of Person. Friends who have programming experience know some initialization methods. Here are some common attributes to initialize, and define some common methods.

Next, all the encapsulation needs to be addressed.

Packaging

For encapsulation, classes can encapsulate a way (large encapsulation) that we mentioned above has common attributes and behaviors. While encapsulation is not limited to classes, functions can encapsulate some common operations. The following knowledge is encapsulation, but the encapsulation method will be slightly different, let's not talk about encapsulation knowledge first.

Let's start with a simple understanding of the initialization method. The _init_() method in the python class is a way to initialize some properties of an object, but this method is not to create an object. When we create classes, this _init_() method means that we need to place some common properties that we consider multiple objects and some operations that need to be initialized (call methods). Since the _init_() method is not the method of creating objects, what is the method of creating objects? _ The new_() method. I believe that my friends have seen this method. This method will be called automatically when creating a class, and we do not need to write it out (it will be written out later for testing). This makes it clear that when creating an object, you first call the _new_() method to return an object, and then call the _init_() method to initialize the properties of the object.

class Person:
    def __new__(cls, *args, **kwargs):
        # Parent Class Call__new__()Return an object
        return super().__new__(cls)

    def __init__(self, high, weight):
        self.high = high
        self.weight = weight


person = Person(12, 135)

There can be many attributes in a class, and many of what I'm talking about are not the number of attributes, nor the type of attribute values, but the type of attributes. The comments in the following code can be ignored

The types of attributes are: class attributes, class private attributes, class protection attributes, instance attributes, instance private attributes, instance protection attributes. The protection attributes and private attributes mentioned here are not strictly explained in python, but the functions or use of reservations.

Class attributes:

Both classes and instances can modify and access class attributes directly

Accessing and modifying class attributes through instances in instance methods

Accessing and modifying class properties through class names in class methods

Accessing and modifying private attributes of classes through class names in static methods

If an instance has instance attributes with the same name as class attributes, then modification and access have nothing to do with class attributes

class Person:
    # Initial value of protected attribute of class "12"
    count = "12"

    def __init__(self, high, weight):
        self.high = high
        self.weight = weight

    def self_set_count(self, count):
        self.count = count

    def self_get_count(self):
        return self.count

    # Class method
    @classmethod
    def class_set_count(cls, count):
        cls.count = count

    @classmethod
    def class_get_count(cls):
        return cls.count

    # Static method
    @staticmethod
    def static_set_count(count):
        Person.count = count

    @staticmethod
    def static_get_count():
        return Person.count


person = Person(12, 135)
# Instances modify and access the protected properties of classes directly
person.count = "24"
print(person.count)
# Class name directly modifies and accesses class protection attributes
Person.count = "36"
print(Person.count)

# Instance calls instance methods to modify and access private attributes of classes
person.self_set_count("24")
print(person.self_get_count())  # 24
# Class Name Calls Class Method to Modify and Access Class Private Properties
Person.class_set_count("36")
print(Person.class_get_count())  # 36

# Instance calls static methods to modify and access private properties of classes
person.static_set_count("24")
print(person.static_get_count())  # 24
# Class names call static methods to modify and access private properties of classes
Person.static_set_count("36")
print(Person.static_get_count())  # 36

2. Private attributes of classes:

Accessing and modifying private attributes of classes through instances in instance methods

Accessing and modifying private attributes of classes through class names in class methods

Accessing and modifying private properties of classes through class names in static methods

Both classes and instances are inaccessible; if instances have instance private attributes with the same name as class private attributes, modification and access have nothing to do with class private attributes

class Person:
    # Class Attribute Initial Value 12
    count = 12
    # Class's Private Attribute Initial Value "12"
    __string = "12"

    def __new__(cls, *args, **kwargs):
        return super().__new__(cls)

    def __init__(self, high, weight):
        self.high = high
        self.weight = weight
    
    def self_set_string(self, string):
        self.__string = string
    
    def self_get_string(self):
        return self.__string
    
    # Class method
    @classmethod
    def class_set_string(cls, string):
        cls.__string = string
    
    @classmethod
    def class_get_string(cls):
        return cls.__string
    
    #Static method
    @staticmethod
    def static_set_string(string):
        Person.__string = string
    
    @staticmethod
    def static_get_string():
        return Person.__string


person = Person(12, 135)
# Instances modify and access class properties
person.count = 24
print(person.count)    # 24
# Class name modification and access to class properties
Person.count = 36
print(Person.count)    # 36

# Instance calls instance methods to modify and access private attributes of classes
person.self_set_string("24")
print(person.self_get_string())    # 24
# Class Name Calls Class Method to Modify and Access Class Private Properties
Person.class_set_string("36")
print(Person.class_get_string())    # 36

# Instance calls static methods to modify and access private properties of classes
person.static_set_string("24")
print(person.static_get_string())    # 24
# Class names call static methods to modify and access private properties of classes
Person.static_set_string("36")
print(Person.static_get_string())    # 36

3. Protection attributes of classes:

Accessing and modifying the protected properties of classes through classes and instances outside of classes

Accessing and modifying class protection attributes through instances in instance methods

Accessing and modifying protected attributes of classes through class names in class methods

Accessing and modifying protected properties of classes through class names in static methods

Both classes and instances are inaccessible outside the module; if an instance has instance protection attributes with the same name as the class protection attributes, then modification and access have nothing to do with the class protection attributes

class Person:
    # Initial value of protected attribute of class "12"
    _protection = "12"

    def __init__(self, high, weight):
        self.high = high
        self.weight = weight
    
    def self_set_protection(self, protection):
        self._protection = protection
    
    def self_get_protection(self):
        return self._protection
    
    # Class method
    @classmethod
    def class_set_protection(cls, protection):
        cls._protection = protection
    
    @classmethod
    def class_get_protection(cls):
        return cls._protection
    
    #Static method
    @staticmethod
    def static_set_protection(protection):
        Person._protection = protection
    
    @staticmethod
    def static_get_protection():
        return Person._protection


person = Person(12, 135)
# Instances modify and access the protected properties of classes directly
person._protection = "24"
print(person._protection)
# Class name directly modifies and accesses class protection attributes
Person._protection = "36"
print(Person._protection)

# Instance calls instance methods to modify and access private attributes of classes
person.self_set_protection("24")
print(person.self_get_protection())    # 24
# Class Name Calls Class Method to Modify and Access Class Private Properties
Person.class_set_protection("36")
print(Person.class_get_protection())    # 36

# Instance calls static methods to modify and access private properties of classes
person.static_set_protection("24")
print(person.static_get_protection())    # 24
# Class names call static methods to modify and access private properties of classes
Person.static_set_protection("36")
print(Person.static_get_protection())    # 36

4. Instance attributes:

Access and modify instance attributes through classes and instances outside of classes

Accessing and modifying instance attributes through instances in the instance method

Accessing and modifying instance properties through class names in class methods

Access and modify instance properties through class names in static methods

If an instance has instance attributes with the same name as class attributes, then modification and access have nothing to do with class attributes

class Person:

    def __init__(self, high, weight):
        # Instance attributes
        self.high = high
        self.weight = weight

    def self_set_high(self, high):
        self.high = high

    def self_get_high(self):
        return self.high

    # Class method
    @classmethod
    def class_set_high(cls, high):
        cls.high = high

    @classmethod
    def class_get_high(cls):
        return cls.high

    # Static method
    @staticmethod
    def static_set_high(high):
        Person.high = high

    @staticmethod
    def static_get_high():
        return Person.high


person = Person(12, 135)
# Instances modify and access the protected properties of classes directly
person.high = "24"
print(person.high)
# Class name directly modifies and accesses class protection attributes
Person.high = "36"
print(Person.high)

# Instance calls instance methods to modify and access private attributes of classes
person.self_set_high("24")
print(person.self_get_high())  # 24
# Class Name Calls Class Method to Modify and Access Class Private Properties
Person.class_set_high("36")
print(Person.class_get_high())  # 36

# Instance calls static methods to modify and access private properties of classes
person.static_set_high("24")
print(person.static_get_high())  # 24
# Class names call static methods to modify and access private properties of classes
Person.static_set_high("36")
print(Person.static_get_high())  # 36

5. Private attributes of instances:

Access and modify instance private attributes through instances in the instance method

Accessing and modifying instance private properties through class names in class methods

Accessing and modifying instance private properties through class names in static methods

Accessing and modifying instance private attributes by classes and instances outside of a class is equivalent to adding an attribute dynamically, so it is not accessible outside a class; if an instance has instance private attributes with the same name as the private attributes of a class, then modifying and accessing have nothing to do with class private attributes

class Person:

    def __init__(self, high, weight):
        # Instance attributes
        self.high = high
        self.__weight = weight

    def self_set_weight(self, weight):
        self.__weight = weight

    def self_get_weight(self):
        return self.__weight

    # Class method
    @classmethod
    def class_set_weight(cls, weight):
        cls.__weight = weight

    @classmethod
    def class_get_weight(cls):
        return cls.__weight

    # Static method
    @staticmethod
    def static_set_weight(weight):
        Person.__weight = weight

    @staticmethod
    def static_get_weight():
        return Person.__weight


person = Person(12, 135)
# Here are the dynamically added attributes of instances
person.__weight = "24"
print(person.__weight)
# Here are the properties of the dynamic addition of class names
Person.__weight = "36"
print(Person.__weight)

# Instance calls instance methods to modify and access private attributes of classes
person.self_set_weight("24")
print(person.self_get_weight())  # 24
# Class Name Calls Class Method to Modify and Access Class Private Properties
Person.class_set_weight("36")
print(Person.class_get_weight())  # 36

# Instance calls static methods to modify and access private properties of classes
person.static_set_weight("24")
print(person.static_get_weight())  # 24
# Class names call static methods to modify and access private properties of classes
Person.static_set_weight("36")
print(Person.static_get_weight())  # 36

6. Protection attributes of instances:

Attribute protection through instance access and modification in the instance method

Accessing and modifying instances to protect attributes through class names in class methods

Accessing and modifying instances to protect properties through class names in static methods

Accessing and modifying instance protection attributes through classes and instances outside a class is equivalent to dynamically adding an attribute to itself, so it is not accessible outside a class; if an instance has instance private attributes with the same name as the private attributes of a class, then modifying and accessing have nothing to do with class private attributes   

class Person:

    def __init__(self, high, weight):
        # Instance attributes
        self.high = high
        # Instance protection attributes
        self._weight = weight

    def self_set_weight(self, weight):
        self._weight = weight

    def self_get_weight(self):
        return self._weight

    # Class method
    @classmethod
    def class_set_weight(cls, weight):
        cls._weight = weight

    @classmethod
    def class_get_weight(cls):
        return cls._weight

    # Static method
    @staticmethod
    def static_set_weight(weight):
        Person._weight = weight

    @staticmethod
    def static_get_weight():
        return Person._weight


person = Person(12, 135)
# Here are the dynamically added attributes of instances
person._weight = "24"
print(person._weight)
# Here are the properties of the dynamic addition of class names
Person._weight = "36"
print(Person._weight)

# Instance calls instance methods to modify and access private attributes of classes
person.self_set_weight("24")
print(person.self_get_weight())  # 24
# Class Name Calls Class Method to Modify and Access Class Private Properties
Person.class_set_weight("36")
print(Person.class_get_weight())  # 36

# Instance calls static methods to modify and access private properties of classes
person.static_set_weight("24")
print(person.static_get_weight())  # 24
# Class names call static methods to modify and access private properties of classes
Person.static_set_weight("36")
print(Person.static_get_weight())  # 36

Attributes involved in classes are illustrated with examples (pro-test validity), but there are several methods in classes, and this method is also the key. Class Method Types: Class Method, Instance Method, Static Method

The main thing is to verify who can call the three methods

The above code has verified that instances can call instance methods, class names can call class methods, and class names can call static methods.

Instances can call class methods and static methods

Class names can call instance methods, and the reference must pass a specific instance

class Person:

    def __init__(self, high, weight):
        # Instance attributes
        self.high = high
        # Instance protection attributes
        self._weight = weight

    def self_set_weight(self, weight):
        self._weight = weight

    def self_get_weight(self):
        return self._weight

    # Class method
    @classmethod
    def class_set_weight(cls, weight):
        cls._weight = weight

    @classmethod
    def class_get_weight(cls):
        return cls._weight

    # Static method
    @staticmethod
    def static_set_weight(weight):
        Person._weight = weight

    @staticmethod
    def static_get_weight():
        return Person._weight


person = Person(12, 135)

# Instance Call Class Method
person.class_set_weight("24")
print(person.class_get_weight())  # 24
# Instance call static method
person.static_set_weight("36")
print(person.static_get_weight())  # 36

# Class name calls instance method, the first parameter must be a concrete instance
Person.self_set_weight(person, "24")
print(Person.self_get_weight(person))  # 24

Summary:

Object names can call static methods, instance methods, class methods

2. Class names can call static methods, class methods and instance methods, but when calling instance methods, the first parameter self needs to be passed in, which is actually the object itself, without parameter error reporting.

3. Instance attributes are accessed through <self. > of instance methods, while static methods and class methods cannot access instance attributes.

4. Class attributes are accessed through <cls. > of class methods, or within other functions by <class name. >.

Posted by hasin on Mon, 09 Sep 2019 02:58:07 -0700