Advanced Python ----- object-oriented 2.0 (specific properties and methods and private properties and methods)

Table of contents

Foreword:

1. Add unique properties/methods

Example 1: Add unique attributes

 Example 2: Adding a unique method

2. Private properties/methods

(1) Privatization example 

(2) Private properties/methods can be used inside the class

(3) Mandatory access to privatized properties/methods

(4) @property decorator to operate private properties/methods

Summarize:


Foreword:

        Earlier we learned the definition of attributes and methods in Python, but these attributes and methods are public, that is to say, I define a single or multiple instance objects, and these instance objects share the attributes and methods of this class, and can also to access these properties and methods. (The previous link was Python Advanced -----Object-Oriented 1.0 (Introduction and Definition of Objects and Classes)_Python Ouni Sauce's Blog-CSDN Blog ) Here is an example:

class People:
    ty='人类'
    def __init__(self,name,age,gander):
        self.name=name
        self.age=age
        self.gander=gander
    def fun(self):
        print('电话号码****')
        print(f'我的年龄{self.age}')

a=People('Jack',15,'male')
print(a.ty)
print(a.name,a.age,a.gander)
a.fun()
#输出结果:人类
# Jack 15 male
# 电话号码****
# 我的年龄15

It can be seen here that all properties and methods of this instance object can be accessed, and the properties and methods of this class are public and not unique.

1. Add unique properties/methods

When we create an instantiated object, we can manually add the properties and methods of the object. The added methods or properties are unique to this object. If we create another object, this object cannot be accessed. A unique property or method of an object.

Example 1: Add unique attributes

class People:
    def __init__(self, name, age, gander):
        self.name = name
        self.age = age
        self.gander = gander
    def fun(self):
        print('电话号码****')
        print(f'我的年龄{self.age}')
a = People('Jack', 15, 'male')
b=  People('Amy',16,'fmale')
a.father='Tom'
print(a.__dict__)
print(b.__dict__)
print(b.father)#报错:'People' object has no attribute 'father'
#输出结果:{'name': 'Jack', 'age': 15, 'gander': 'male', 'father': 'Tom'}
#         {'name': 'Amy', 'age': 16, 'gander': 'fmale'}

As you can see here, I added the father attribute to object a, and then checked these attributes through the __dict__ method. Compared with object b, I found that there is an additional father attribute, then this attribute is a unique attribute of object a, so if I go to Use object b to query b.father, then the result will report an error

 Example 2: Adding a unique method

class People:
    def __init__(self, name, age, gander):
        self.name = name
        self.age = age
        self.gander = gander
    def fun(self):
        print('电话号码****')
        print(f'我的年龄{self.age}')
def specific():
    print('this is a specific function')
a = People('Jack', 15, 'male')
b= People('Amy',16,'fmale')
b.specific=specific
b.specific()
#a.specific() #报错:'People' object has no attribute 'specific'
#输出结果:this is a specific function
#可以通过以下的方法,查询到对象a和对象b支持的功能和方法,很显然就可以看出specific()方法是谁特有的
# print(dir(b))
# print(dir(a))

It can be seen here that I added a unique method specific() to object b, so object b can call this method, but object a cannot call it, otherwise an error will be reported

2. Private properties/methods

         The so-called private means that in all data, some data is specially set to be unquerable, which means encryption. In real life, relevant departments, such as hospitals, have obtained our personal information, name, gender, age, mobile phone number, ID number, etc., but these departments will not display all the information when they are displayed on some platforms come out (such as age, ID number, etc.), but Zhang, Li, etc. This is a process of encryption and privacy. Encrypt (private) some attributes or methods in the Python class, so that the created instance objects cannot access these attributes or methods, which is a process of privatization.

 Definition of privatization in Python:

Instance object __ attribute name/method name

(that is, add two _ (underscore) in front of the property name or method name

Function:
As mentioned above with the example of the hospital, some information can be encrypted and privatized to play a protective role. It is the same in Python, which plays a protective role and does not disclose some more important information.

(1) Privatization example 

 Example 1: Attribute Privatization

class People:
    def __init__(self, name, age, gander):
        self.name = name
        self.__age = age #这里把年龄信息给加密私有化
        self.gander = gander
    def __user_info(self): #这里吧方法给加密私有化
        print('电话号码****')
        print(f'我的年龄{self.age}')
    def fun(self):
        print('the user')
user=People('Jack',20,'male')
print(user.name) #输出结果:Jack
print(user.gander) #输出结果:male
print(user.__age) #报错: 'People' object has no attribute '__age'

Here I privatize age, but my output is still output according to __age, and the result is an error saying that this attribute does not exist, which also shows that this attribute cannot be queried

Example 2: Method Privatization

class People:
    def __init__(self, name, age, gander):
        self.name = name
        self.__age = age #这里把年龄信息给加密私有化
        self.gander = gander
    def __user_info(self): #这里吧方法给加密私有化
        print('电话号码****')
        print(f'我的年龄{self.age}')
    def fun(self):
        print('the user')
user=People('Jack',20,'male')
user.fun() #输出结果:the user
user.__user_info() #报错:'People' object has no attribute '__user_info'

It can be seen here that __user_info() cannot be called after privatization. The advantage of writing this way is that when we learn object-oriented encapsulation, we can privatize and encapsulate relevant information to avoid leakage of important information and improve protective

(2) Private properties/methods can be used inside the class

        In the process of defining a class, some private properties or methods can be called inside the class, but the external instance object cannot be accessed and called (the example is above).

Example: 

class People:
    def __init__(self, name, age, gander):
        self.name = name
        self.__age = age #这里把年龄信息给加密私有化
        self.gander = gander
    def __user_info(self): #这里吧方法给加密私有化
        print('电话号码****')
        print(f'我的年龄{self.__age}')
    def __fun(self):
        print('the user')
    def using(self):#在类的内部定义一个方法去调用私有化方法/属性
        self.__fun()
        self.__user_info()
a=People('John',22,'male') #外部的实例对象是无法调用私有化属性/方法的
a.using() 
#输出结果:
# the user
# 电话号码****
# 我的年龄22

(3) Mandatory access to privatized properties/methods

        After privatizing the relevant properties/methods, is it inaccessible? Of course not. If you really can’t access it, instead of deprivatizing it, it’s better not to write it. In fact, there are some methods in Python to force access to privatized attributes or methods. This is actually a test of the moral level of programmers. Generally, although we can access some information through some channels, it is really unnecessary. This is not good for other people, so in the future work and life It is not recommended to force access to relevant important information at this time. Back to the topic, I am learning Python now, how can there be any important information, so these methods still need to be learned

 Through dir(), you can query the methods that an object can support. Here you can see that the first two methods have _People__. In fact, we can use this method to query and use some privatized data or methods.

Format:

Instance object_class name__attribute/method

Example:

class People:
    def __init__(self, name, age, gander):
        self.name = name
        self.__age = age #这里把年龄信息给加密私有化
        self.gander = gander
    def __user_info(self): #这里吧方法给加密私有化
        print('电话号码****')
        print(f'我的年龄{self.__age}')
    def fun(self):
        print('the user')
user=People('Tom',20,'male')
print(user._People__age) #强制访问属性
user._People__user_info()  #强制访问方法
#输出结果:20
#       电话号码****
#       我的年龄20

(4) @property decorator to operate private properties/methods

        The @property decorator can turn a method into a property, but this property is not completely a property. The converted property has the effect of a method. This can improve operational efficiency and allow the operator to clearly feel that what is being operated is not a method but an attribute.

usage:

Python provides @property to get the return value attribute of the method, @methodname.setter to set the attribute value returned by the method, @methodname.deleter to delete the return value in the method

 Example:

class Test:
    def __init__(self,score):
        self.__score=score
    @property #装饰器把下面这个方法转换为一个具有方法效果的属性
    def getscore(self): #定义一个方法
        if self.__score>=60:
            return f'及格,分数为{self.__score}'
        return '不及格'
Tom=Test(50)
print(Tom.getscore)

The initial score here is 50 points, and then the return is failed, but if we want to modify or delete this score, we need to use the @getscore.setter and @getscore.deleter decorator methods

class Test:
    def __init__(self,score):
        self.__score=score
    @property #装饰器把下面这个方法转换为一个具有方法效果的属性
    def getscore(self): #定义一个方法
        if self.__score>=60:
            return f'及格,分数为{self.__score}'
        return '不及格'
    @getscore.setter
    def setscore(self,newscore):
        print('分数已修改')
        self.__score=newscore
    @getscore.deleter
    def delscore(self):
        print('分数已删除')
        del self.__score
Tom=Test(50)
#触发property装饰器,查询结果
print(Tom.getscore)
#触发setter装饰器
Tom.setscore=66
print(Tom.getscore)
#触发deleter装饰器
del Tom.delscore
print(Tom.getscore) #这里分数已经被删除了就会报错,'Test' object has no attribute '_Test__score'

In fact, the @property decorator has many more functions. Here I use the property decorator to convert the methods in the class into property functions with method effects. I won’t say much about the others. If you want to know more about For property decorators, you can check out this link http://t.csdn.cn/4Ey3m

Summarize:

Attributes and methods are an important part of object-oriented, which are divided into public, specific, and private .

Shared : all instances of the same class can access

Unique : Although instance objects of the same class, some attributes are unique to an instance object, and other instance objects cannot be accessed

Private : Private is defined in the class, and the related properties/methods are set to not allow access. Instance objects of the same class have their private properties, but access is not allowed

 Well, that's it for this issue, get out of class is over!

Share a wallpaper~

 

Guess you like

Origin blog.csdn.net/m0_73633088/article/details/129292326