Object Oriented: Membership of Classes

I. Components of subcategories

As we have mentioned before, classes can be roughly divided into two areas, as shown in the following figure:

Detailed division of each area can be divided into:

class A:

    company_name = 'Education for Old Boys'  # Static variables (static fields)
    __iphone = '1353333xxxx'  # Private static variables (private static fields)


    def __init__(self,name,age): #Special methods

        self.name = name  #Object properties (common fields)
        self.__age = age  # Private Object Properties (Private Common Fields)

    def func1(self):  # General method
        pass

    def __func(self): #Private methods
        print(666)


    @classmethod  # Class method
    def class_func(cls):
        """ Define class methods, at least one cls parameter """
        print('Class method')

    @staticmethod  #Static method
    def static_func():
        """ Define static methods without default parameters"""
        print('Static method')

    @property  # attribute
    def prop(self):
        pass

II. Private Members of Category

There are two forms for members of each class:

  • Public members, accessible anywhere
  • Private members, only within a class can approach

Private and public members have different access restrictions:

Static fields (static properties)

  • Public static fields: classes can be accessed; classes can be accessed internally; derived classes can be accessed
  • Private static fields: accessible only within the class;
class C:

    name = "Public static fields"

    def func(self):
        print C.name

class D(C):

    def show(self):
        print C.name


C.name         # Class access

obj = C()
obj.func()     # Class can be accessed internally

obj_son = D()
obj_son.show() # Accessible in derived classes

//Public static fields

Public static properties (fields)

class C:

    __name = "Private static fields"

    def func(self):
        print C.__name

class D(C):

    def show(self):
        print C.__name


C.__name       # No external access

obj = C()
obj.__name  # No external access
obj.func()     # Class can be accessed internally   

obj_son = D()
obj_son.show() #Not accessible in derived classes  

//Private static fields

Private static properties (fields)

Ordinary fields (object properties)

  • Common common fields: objects can be accessed; classes can be accessed internally; derived classes can be accessed
  • Private common fields: accessible only within the class;
class C:
    
    def __init__(self):
        self.foo = "Public field"

    def func(self):
        print self.foo  #Class internal access

class D(C):
    
    def show(self):
        print self.foo # Access in Derived Classes

obj = C()

obj.foo     # Object access
obj.func()  # Class internal access

obj_son = D();
obj_son.show()  # Access in Derived Classes

//Common Common Field

Public Object Attributes

class C:
    
    def __init__(self):
        self.__foo = "Private field"

    def func(self):
        print self.foo  #Class internal access

class D(C):
    
    def show(self):
        print self.foo # Access in Derived Classes

obj = C()

obj.__foo     # Object access ==> error
obj.func()  # Class internal access ==> correct

obj_son = D();
obj_son.show()  # Access==> Error in Derived Class

//Private common fields

Private Object Properties

Method:

  • Public methods: objects can be accessed; classes can be accessed internally; derived classes can be accessed
  • Private methods: accessible only within the class;
class C:

    def __init__(self):
        pass
    
    def add(self):
        print('in C')

class D(C):

    def show(self):
        print('in D')
        
    def func(self):
        self.show()
obj = D()
obj.show()  # Object access   
obj.func()  # Class internal access    
obj.add()  # Access in Derived Classes  

//public Method

public Method

class C:

    def __init__(self):
        pass

    def __add(self):
        print('in C')

class D(C):

    def __show(self):
        print('in D')

    def func(self):
        self.__show()
obj = D()
obj.__show()  # By not accessing objects
obj.func()  # Class can be accessed internally
obj.__add()  # Not accessible in derived classes

Private methods

Summary:

For these private members, they can only be used inside classes, not outside classes or derived classes.

* ps: To access private members, you can use the object. class attribute name, but absolutely not!!!!*

* Why can it be accessed through. class private member name? Because when a class is created, if it encounters a private member (including private static fields, private common fields, private methods), it will save it in memory and automatically add the class name in front of it.*

Other members of the class

The other members here are mainly class methods:

Methods include: common method, static method and class method. All three methods belong to class in memory. The difference is that they are called in different ways.

Example method

Definition: The first parameter must be the instance object. The parameter name is generally agreed to be "self", through which the attributes and methods of the instance can be passed (or the attributes and methods of the class can be passed).

Call: Called only by instance objects.

Class method

Definition: Use the decorator @class method. The first parameter must be the current class object. The parameter name is generally agreed to be "cls", through which the class attributes and methods can be passed (the attributes and methods of instances can not be passed);

Call: Both instance and class objects can be invoked.

Static method

Definition: Use the decorator @static method. The parameters are arbitrary and there are no "self" and "cls" parameters, but no attributes and methods of classes or instances can be used in the body of the method.

Call: Both instance and class objects can be invoked.

Double-bottom approach (as I'll talk about later)

Definition: The double-bottom method is a special method, which is provided by the interpreter. It is a special method by the interpreter. The double-bottom method is mainly used by python source programmers.

We try not to use the double-bottom method in our development, but it is more beneficial for us to read the source code if we study the double-bottom method in depth.

Call: Different double-bottom methods have different trigger modes, just like the trigger mechanism when robbing a grave. Unconsciously, they trigger double-bottom methods, such as init.

Example method

In short, instance methods are the methods that instances of classes can use. There's not much explanation here.

Class 3.1 Methods

Use the decorator @class method.

In principle, the class method is a method of manipulating the class itself as an object. Assuming that there is a method that logically uses the class itself as an object to invoke, then this method can be defined as a class method. In addition, class methods can also be defined if inheritance is required.

The following scenario:

Suppose I have a student class and a class class class class. The functions I want to achieve are:
Implement the operation of increasing the number of classes and obtain the total number of classes;
The student class inherits from the class class class, and the class size increases with each instantiation of a student.
Finally, I want to define some students and get the total number of students in the class.

Think: It's more appropriate to use the class method to solve this problem. Why? Because I instantiate the students, but if I get the total number of classes from the example of students, it is logically unreasonable. At the same time, if you want to get the total number of classes, it is not necessary to generate a class instance.

class Student:
    
    __num = 0
    def __init__(self,name,age):
        self.name = name
        self.age= age
        Student.addNum()  # Writing in the _new_ method is appropriate, but I haven't learned it yet. Let's put it here for the moment.
        
    @classmethod
    def addNum(cls):
        cls.__num += 1

    @classmethod
    def getNum(cls):
        return cls.__num



a = Student('Platinum star', 18)
b = Student('Martial sir', 36)
c = Student('alex', 73)
print(Student.getNum())

3.2 Static Method

Use the decorator @static method.

Static methods are functions in classes and do not require instances. Static methods are mainly used to store logical code. They belong to classes logically, but they have nothing to do with classes themselves. That is to say, in static methods, they do not involve the operation of attributes and methods in classes. It can be understood that the static method is a separate, simple function, which is only hosted in the namespace of a class for easy use and maintenance.

For example, I want to define a class about time operations, which has a function to get the current time.

import time

class TimeTest(object):
    def __init__(self, hour, minute, second):
        self.hour = hour
        self.minute = minute
        self.second = second

    @staticmethod
    def showTime():
        return time.strftime("%H:%M:%S", time.localtime())


print(TimeTest.showTime())
t = TimeTest(2, 10, 10)
nowTime = t.showTime()
print(nowTime)

As mentioned above, static methods (functions) are used, but attributes (or methods) of classes or instances are not used (and cannot be used) in the body of the method. To get a string of the current time, you don't necessarily need to instantiate the object. For static methods, the class is more like a namespace.

In fact, we can also write the same function outside the class to do these things, but doing so will disrupt the logical relationship, and will lead to difficulties in code maintenance in the future.

3.3 Attributes

What is feature property?

Property is a special property that is accessed by performing a function and returning a value.

Example 1: BMI index (bmi is calculated, but obviously it sounds like an attribute rather than a method, if we make it an attribute, it's easier to understand)

BMI values for adults:
Too light: below 18.5
 Normal: 18.5-23.9
 Overweight: 24-27
 Obesity: 28-32
 Very obese, over 32
 Body mass index (BMI) = body weight (kg) = height ^ 2 (m)
  EX: 70kg÷(1.75×1.75)=22.86
class People:
    def __init__(self,name,weight,height):
        self.name=name
        self.weight=weight
        self.height=height
    @property
    def bmi(self):
        return self.weight / (self.height**2)

p1=People('egon',75,1.85)
print(p1.bmi)

//Example Code

View Code

Why use property?

After defining a function of a class as a feature, obj.name can not be perceived when the object is reused. It is calculated by executing a function. The use of this feature follows the principle of uniform access.

** Because there are three access modes in the new class, we can define three methods as the same attribute according to the access characteristics of their attributes: acquisition, modification and deletion.

class Foo:
    @property
    def AAA(self):
        print('get Run me when it's time.')

    @AAA.setter
    def AAA(self,value):
        print('set Run me when it's time.')

    @AAA.deleter
    def AAA(self):
        print('delete Run me when it's time.')

#Only after attribute AAA defines property can AAA.setter,AAA.deleter be defined.
f1=Foo()
f1.AAA
f1.AAA='aaa'
del f1.AAA

//Or:
class Foo:
    def get_AAA(self):
        print('get Run me when it's time.')

    def set_AAA(self,value):
        print('set Run me when it's time.')

    def delete_AAA(self):
        print('delete Run me when it's time.')
    AAA=property(get_AAA,set_AAA,delete_AAA) #Built-in property three parameters and get,set,delete one-to-one correspondence

f1=Foo()
f1.AAA
f1.AAA='aaa'
del f1.AAA

View Code

class Goods(object):

    def __init__(self):
        # Original price
        self.original_price = 100
        # Discount?
        self.discount = 0.8

    @property
    def price(self):
        # Real price = original price * discount
        new_price = self.original_price * self.discount
        return new_price

    @price.setter
    def price(self, value):
        self.original_price = value

    @price.deltter
    def price(self, value):
        del self.original_price

obj = Goods()
obj.price         # Acquire commodity prices
obj.price = 200   # Modify the original price of goods
del obj.price     # Delete the original price of goods

//Examples of commodities

Commodity examples

IV. isinstace and issubclass

class A:
    pass

class B(A):
    pass

obj = B()


print(isinstance(obj,B))
print(isinstance(obj,A))

isinstance

isinstance(a,b): Determine whether a is an object instantiated by class B (or a derived class of class b)

class A:
    pass

class B(A):
    pass

class C(B):
    pass

print(issubclass(B,A))
print(issubclass(C,A))

issubclass

issubclass(a,b): Determine whether class A is a derived class of class B (or a derived class of b)

Think: So what is the relationship between list str tuple dict and other classes and Iterble classes?

from collections import Iterable

print(isinstance([1,2,3], list))  # True
print(isinstance([1,2,3], Iterable))  # True
print(issubclass(list,Iterable))  # True

# As can be seen from the examples above, these iterative data types, list str tuple dict, etc., are all subclasses of Iterable.

View Code

Extracurricular understanding: meta type.

According to Python's theory that everything is an object, a class is also an object. Where is the object of a class instantiated?

print(type('abc'))
print(type(True))
print(type(100))
print(type([1, 2, 3]))
print(type({'name': 'Platinum star'}))
print(type((1,2,3)))
print(type(object))

class A:
    pass

print(isinstance(object,type))
print(isinstance(A, type))

View Code

The type metaclass is the class that obtains the subordinate of the object, and the type class is special. The Python principle is that everything is an object, and its class can also be understood as an'object'. The type metaclass is also called a construction class. Most built-in classes (including objects) and their own defined classes in Python are created by the type metaclass.

* The relationship between type class and object class is unique: object is an instance of type class, and type class is a subclass of object class. This relationship is magical and can not be expressed by python code, because the other must exist before defining one. So this is only for understanding.

Keywords: PHP Attribute Python

Added by osti on Wed, 07 Aug 2019 11:04:56 +0300