Python object-oriented (3)

Private permissions

The meaning of encapsulation:
put attributes and methods together as a whole, and then process them by instantiating objects;
hide internal implementation details, only need to interact with objects and their attributes and methods;
add attributes and methods to classes Access control.

Private permission: add two underscores in front of the property name and method name __
The private properties and private methods of the class cannot be accessed directly through the object, but can be accessed within the class;
the private properties and private methods of the class will not be accessed. Inherited by subclasses, subclasses cannot access them;
private properties and private methods are often used to deal with the internal affairs of the class, not through object processing, which plays a security role.
insert image description here
Output result:
insert image description here
Implementation code:

class Person(object):
    def __init__(self,name,score):
        self.name = name
        self.__score = score
    def _primethod(self):
        print("私有方法")
p = Person("Bob",59)
print(p.name)
print(p.__primethod)

Class department calls private properties and private methods

demo: Private methods and private properties
Subclasses call private properties and methods through instance methods, but cannot be called directly
insert image description here
Output result:
insert image description here

class Person(object):
    def __init__(self,name,score):
        self.name = name
        self.__score = score
    def __primethod(self):
        print("私有方法")
    def method(self):
        return self.__score
    def method1(self):
        return self.__primethod()
p = Person("Bob",59)
print(p.method())
p.method1()

Subclasses cannot inherit parent class private properties and methods

insert image description here
Output result:
insert image description here
Implementation code:

class Father(object):
    def __init__(self,name):
        self.name = name
        self.__age = 19
    def eat(self):
        print("吃东西")
    def __playPingPang(self):
        print("喜欢玩乒乓球")
class Son(Father):
    pass
son = Son("张三")
print(son.name)
print(son.__age)

Summary:
1). Private properties, which can be called from within the class through self, but cannot be accessed through the object
2). Private methods, which can be called from within the class through self, but cannot be accessed through the object
3). Objects cannot access properties with private permissions and method
4). Subclasses cannot inherit the properties and methods of parent class private permissions.
5). In Python, there are no keywords like public and private, protected in C++ to distinguish public and private attributes.
6). Python is distinguished by attribute naming. If two underscores '__' are added before the attribute and method name, it indicates that the attribute and method are private permissions, otherwise they are public permissions.

Modify the value of a private property

insert image description here
Output result:
insert image description here
Implementation code:

class People(object):
    def __init__(self):
        self.__money = 1000
    def set_money(self,money):
        self.__money = money
    def get_money(self):
        return self.__money
p = People()
p.set_money(2000)
print(p.get_money())

Summary:
In modern software development, get_xxx() methods and set_xxx() methods are usually defined to obtain and modify private property values
​​get_xxx() methods –> return the value of private properties
set_xxx() methods –> receive parameters, modify the value of private properties The value
object cannot access the properties and methods of private permissions. You can modify the value of the private property by accessing the public method set_money(), and you can obtain the value of the private property by accessing the public method get_money().

Class and instance properties

Class attributes and instance attributes
After understanding the basic things about classes, let's take a look at the difference between these concepts in python.
Let's talk about class attributes and instance attributes.
In the previous example, what we touched is instance attributes (instance object attributes). ), as the name suggests, a class attribute is an attribute owned by a class object, which is shared by all instance objects of the class object, and there is only one copy in the memory, which is somewhat similar to the static member variable of a class in C++. For public class properties, they can be accessed through class or instance objects.
Instance properties can only be called through objects, not classes.

insert image description here
Output result:
insert image description here
Implementation code:

class People(object):
    name = 'Tom'  # 公有的类属性
    __age = 12  # 私有的类属性

p = People()
print(p.name)  # 正确
print(People.name)  # 正确
print(p.__age)  # 错误,不能在类外通过实例对象访问私有的类属性
print(People.__age) # 错误,不能在类外通过类访问私有的类属性

Can be called through a class or instance object (not private)

instance properties (object properties)

insert image description here
Output result:
insert image description here
Implementation code:

class People(object):
    address = "山东" #类属性
    def __init__(self):
        self.name = "小王" #实例属性
        self.age = 20  #实例属性
p = People()
p.age = 12
print(p.address) #正确
print(p.name) #正确
print(p.age) #正确
print(People.address) #正确
print(People.name) #错误
print(People.age) #错误

Can be called by instantiating objects, classes cannot

Class properties cannot be modified by instance (object)

insert image description here
Output result:
insert image description here
Implementation code:

class People(object):
    country = "china" #类属性
print(People.country)
p = People()

print(p.country)
p.country = "japan"
print(p.country)
p2 = People()
print(p2.country)

static methods and class methods

  1. A class method
    is a method owned by a class object. It needs to be identified as a class method with the decorator @classmethod. For a class method, the first parameter must be the class object, usually with cls as the first parameter (of course, other names can be used) The variable as its first parameter, but most people are used to 'cls' as the name of the first parameter, it is better to use 'cls'), which can be accessed through the instance object and class name.

insert image description here
Output result;
insert image description here
implementation code:

class People(object):
    age = 18
    # 类方法,用classmethod来进行修饰
    @classmethod
    def get_country(cls):
        return cls.age
p = People()
print(p.get_country()) #可以通过实例对象引用
print(People.get_country()) #可以通过类名引用

Another use of class methods is to modify class properties:
insert image description here
output results:
insert image description here
implementation code:

class People(object):
    # 类属性
    age= 18
    #类方法,用classmethod来进行修饰
    @classmethod
    def get_country(cls):
        return cls.age
    @classmethod
    def set_country(cls,age):
        cls.age = age
p = People()
print(p.get_country())   #可以用过实例对象访问
print(People.get_country())    #可以通过类访问
p.set_country(23)
print(p.get_country())
print(People.get_country())
p1 = People()
print(p1.get_country())

The result shows that after the class attribute is modified with the class method, the access through the class name and instance object has changed (all changes)

2. Static methods

It needs to be decorated by the decorator @staticmethod. Static methods do not need to define multiple parameters and can be accessed through objects and classes.
insert image description here
Output result:
insert image description here
Implementation code:

class People(object):
    country = "china"
    @staticmethod
    # 静态方法
    def get_country():
        return People.country
p = People()
#通过对象访问静态方法
print(p.get_country())
# 通过类访问静态方法
print(People.get_country())

There is no need to define additional parameters in static methods, and static methods can be called through objects or classes

3. Instance Methods

The first parameter in an instance method is self, which can only be accessed through the object.
insert image description here
Output result:
insert image description here
Implementation code:

class People(object):
    def selfmethod(self):
        print("我是实例方法")
p = People()
p.selfmethod()
People.selfmethod() #报错

The self parameter is required in the instance method, so calling the instance method needs to be called through the instance object

Summary:
Class methods are decorated with @classmethod, and the first parameter is the class (cls), which can be called through an instance of the class or the class itself.
Static methods are decorated with @staticmethod and can be called using an instance of the class or the class itself.
When an instance method is defined, the first parameter is an instance of the class (self), and it must be called through the instance when it is called.

__new__ method

insert image description here
Output result:
insert image description here
Implementation code:


class A(object):
    def __init__(self):
        print("这是__init__方法")

    def __new__(cls, *args, **kwargs):
        print("这是__new__方法")
        return object.__new__(cls)

a = A()

Summary
1). __new__ must have at least one parameter cls, which represents the class to be instantiated. This parameter is automatically provided by the Python interpreter during instantiation

2). __new__ must have a return value and return the instantiated instance. This point should be paid special attention to when implementing __new__ by yourself. You can return the instance from the parent class __new__, or directly the __new__ of the object out example

3). __init__ has a parameter self, which is the instance returned by this __new__, __init__ can complete some other initialization actions on the basis of __new__, __init__ does not need to return a value

4). We can compare it to a manufacturer. The __new__ method is the early stage of purchasing raw materials, and the __init__ method is to process and initialize the commodity on the basis of raw materials.

singleton pattern

Singleton mode: Always use one object to get an instance, to avoid wasting resources by creating too many instances
Essence : When using the __new__ method to create a new class object, first determine whether it has been created, and if it has been created, use the existing object
insert image description here
Output result:
insert image description here
Implementation code :

class Foo(object):
   instance = None
   def __init__(self):
      self.name = 'alex'
   def __new__(cls):
      if Foo.instance:
         return Foo.instance
      else:
         Foo.instance = object.__new__(cls)
         return Foo.instance
obj1 = Foo()
obj2 = Foo()
print(obj1,obj2)

Guess you like

Origin blog.csdn.net/shitoureng/article/details/124213581