程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Detailed explanation of attribute management mechanism in Python

編輯:Python

Catalog

One 、 Private property

Two 、 Property restrictions -__slots__ Method

3、 ... and 、python How to declare variables in

Four 、python Properties in

One 、 Private property

Python There is no real privatization support , But you can use underscores to get pseudo private , There is one most Python The code follows the habit : Underlined , The name of the prefix should be treated as private API Part of ( Whether it's a function 、 Method or data member )

python Middle private does not realize real private , Just changed the name when saving the attribute , There is no direct method outside

The private attribute is embodied as :

_ Parameter name : Declarative private properties

__ Parameter name : _ Class name + Private property name

class Attributes: attr = 100 # Declarative private properties _attr2 = 999 # _ Class name + Private property name __attr3 = 888print(Attributes.attr)print(Attributes._attr2)

Private property of double underlined , When calling , did not __attr3 This property name , use dict attribute , Check the attribute dictionary :


You can see that the private property that is double underlined is :_ Class name + Private property name

Two 、 Property restrictions -__slots__ Method

I've defined slots Property to restrict the properties of class instances , Only binding slots Specified properties , Can not add slots Other properties

add to slots Other properties , Will report an error directly

class Demo: Use __slots__ Attribute restrictions on objects , Only specified attributes can be added name,age __slots__ = ['name', 'age'] m = Demo()m.name = 111m.age = 18print(m.name,m.age) Then add attributes other than the specified attributes m.sex= male

Execution results :
Report errors :AttributeError: ‘Demo’ object has no attribute ‘sex’ object Demo No, ‘sex’ This attribute

3、 ... and 、python How to declare variables in

grammar : Parameters , Type of attribute

for example :a: int = [11, 22, 3] Parameters a , The type is int , The value is [11, 22, 3]

python Variable or parameter types can be declared in , But in fact, the code execution does not check the type

a: int = "python" # Set up for int type , But the value passed is of string type b: str = 11 # Set to string type , But the value is int type c: list = {11, 22, 33} # Set to list , But passing values is a dictionary print(a, b, c) # ==========》 You can still print out # Type declaration of function parameters :def work(name: str, age: int): # Set to string type and int type print('name The value of is ', name) print('age The value of is ', age)# Actually transfer a list , A dictionary work([11,22,33],{'a':1,'b':2})

Execution results :

Four 、python Properties in

__getattr__ Method :

usage : get attribute , Method triggered when the property does not exist
Special process : When getting properties , Execute first __getattribute__ To see if there are any attributes , Go back when you have , If not, go ahead __getattr__ Method , The return property does not exist

getattribute(self, item):

usage : Property access triggers magic methods , When looking for properties , The method will be called the first time

setattr(self, key, value):

usage : How to set properties , When setting properties , Call this method to set properties

__delattr__ Method :

usage : stay del Trigger when deleting a property , How to delete attributes

class MyDemo(object): def __getattribute__(self, item): """ Property access triggers magic methods :param item: Gets the property name of the :return: Get the attribute value """ print(" The attribute you want to get is :", item) value = super().__getattribute__(item) # Inherited parent class return value def __setattr__(self, key, value): """ How to set properties :param key: Property name :param value: Property value :return: """ print(" The property name you want to set {}, The property value is :{}".format(key, value)) super().__setattr__(key, value) def __delattr__(self, item): """ How to delete attributes :param item: Property name :return: """ print(" The attribute you want to delete is :", item) super().__delattr__(item) def __getattr__(self, item): """ get attribute , Method triggered when the property does not exist :param item: :return: """ print(" Properties obtained {}, non-existent ".format(item)) return 99m = MyDemo()print("************************* Property settings ******************************")# Property settings # Set attribute mode 1 :m.aa = 999m.name = 'musen'# Set attribute mode 2 :setattr Method :setattr(MyDemo(), 'age', 18)print("************************ get attribute *******************************")# get attribute # Mode one :print(m.aa)print(m.name)# Mode two :getattr Method print(getattr(m,'name'))print("************************ Delete attribute ********************************")# Delete attribute # Mode one :del m.aa# Mode two :delattr Method delattr(m, 'age')

This is about python This is the end of the article on the attribute management mechanism in , More about python For the content of attribute management, please search the previous articles of SDN or continue to browse the relevant articles below. I hope you can support SDN more in the future !



  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved