Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the knowledge points of high-order concept attributes in Python

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what are the knowledge points of high-level conceptual attributes in Python". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "what are the knowledge points of high-level concept attributes in Python?"

1. Class attribute

In order to better manage the data in the project, we often need to create custom classes. In Python, classes are also objects, which means they can have their own properties. Let's look at an example.

Class Dog:... Genus = "Canis"... Family = "Canidae"... > Dog.genus'Canis' > > Dog.family'Canidae' > > dir (Dog) ['_ _ class__','_ _ delattr__','_ _ dict__','_ _ dir__','_ doc__','_ eq__','_ format__','_ ge__','_ getattribute__','_ _ gt__','_ _ hash__' '_ _ init__',' _ _ init_subclass__','_ _ le__','_ _ lt__','_ _ module__','_ _ ne__','_ _ new__','_ _ reduce__','_ _ reduce_ex__','_ _ repr__','_ setattr__','_ sizeof__','_ str__','_ _ subclasshook__' '_ _ weakref__',' family', 'genus']

As shown above, we declare a class named Dog. Because all dogs belong to the canine genus and canine family, we have created two class attributes, named genus and family, to store these two pieces of information. As you can see, we can use classes directly to access these properties. We can use the function dir to display a list of dog attributes, including families and genera.

These properties that are defined at the class level are called class attributes, and the class can retrieve them directly. However, unlike other OOP languages, instance objects in Python can also access these class properties directly, as shown in the following code snippet.

> Dog (). Genus' Canis''> Dog (). Family 'Canidae'

two。 Instance property

By customizing the class, we can also set properties for the instance object. These properties are called instance properties, which means that they are instance-specific data. Let's get back to dogs.

Class Dog:... Genus = "Canis"... Family = "Canidae". Def _ _ init__ (self, breed, name):... Self.breed = breed... Self.name = name...

In the above code, we defined the _ _ init__ function, which will be used as a constructor to create a new Dog instance. The first parameter, self, refers to the instance we are creating. During instantiation (that is, creating a new instance), we will assign variety and name information to the new instance object, and these attributes will become part of the instance characteristics, as shown below.

> dog = Dog ("Rottweiler", "Ada") > dog.name'Ada' > dog.breed'Rottweiler'

One thing to note is that we can assign values to instances that have the same properties as the class property. In this case, when you retrieve this property of the instance, the class property will not be retrieved. In other words, when you use an instance object to retrieve the class property, Python first checks whether the instance itself has a property set with the same name. If not, Python uses the class attribute as a fallback. In addition, setting the properties of an instance does not affect the properties of the class with the same name. Let's look at these features in the following code snippet.

> dog.genus = "Felis" > dog.genus'Felis' > Dog ('Poodle',' Cutie'). Genus' Canis'

3. Function as an attribute

In Python, everything is an object, and I mentioned earlier that a class is an object. In addition, the function is a Python object. In a class, we can define functions, often called methods. Depending on how these functions are used, we can further classify them as class methods, static methods, and instance methods. It is not necessary to understand these differences here.

Although some OOP languages treat properties (or functions) and functions as different entities, Python treats these methods (functions) as properties of a class-- not much different from the class attributes we defined earlier. Let's update the Dog class with the three methods mentioned above: class methods, static methods, and instance methods, as shown below.

Class Dog:... Genus = "Canis"... Family = "Canidae". Def _ _ init__ (self, breed, name):... Self.breed = breed... Self.name = name. @ classmethod... Def from_tag (cls, tag_info):... Breed = tag_info ["breed"]... Name = tag_info ["name"]... Return cls (breed, name). @ staticmethod... Def can_bark ():... Print ("Yes. All dogs can bark.") Def bark (self):... Print ("The dog is barking.")

For the updated class, we can use the function dir to check the list of properties of the class. As shown below, both class and static methods are included in the list.

> dir (Dog) ['_ _ class__','_ _ delattr__','_ _ dict__','_ _ dir__','_ _ doc__','_ _ eq__','_ _ format__','_ _ ge__','_ getattribute__','_ gt__','_ hash__','_ _ init__','_ _ init_subclass__' '_ _ le__',' _ _ lt__','_ _ module__','_ _ ne__','_ _ new__','_ _ reduce__','_ _ reduce_ex__','_ _ repr__','_ _ setattr__','_ _ sizeof__','_ str__','_ subclasshook__','_ weakref__', 'bark',' can_bark' 'family',' from_tag', 'genus']

However, one thing that may come as a surprise to some is that the list contains the instance method bark. We know that instance methods are functions that are called by instance objects, so some people may think that these instance methods should be bound to all individual instances. However, this is not the case in Python. Before explaining how the example method works, let's take a look at the following code.

> dog = Dog ("Rottweiler", "Ada") > dog.bark () The dog is barking. Dog.bark (dog) The dog is barking.

As shown above, we first created an instance of the Dog class. Like other OOP languages, instance objects can directly call the instance method bark. However, Python differs from other languages in that the invocation of instance methods operates through classes, calling defined functions (that is, dog .bark (dog)) by passing the instance as parameters. In other words, instance.inst_method () is essentially the same as Class.inst_method (instance) in Python.

You can do this because the Dog class "owns" the instance method, which is a memory-saving mechanism because Python does not need to create a separate copy of the function for each instance object. Instead, when an instance calls an instance method, Python delegates the call to the class, which will call the corresponding function by passing the instance (it will be set to the self parameter in the defined function).

4. Private attribute

If you have OOP experience, you should not be unfamiliar with the existence of access modifiers, such as public, private, and protected. These modifiers limit the scope of access to modified properties and functions. However, you rarely hear such a discussion in Python. In fact, if you borrow the terminology in OOP, all Python properties are public. As shown above, class and instance properties are freely accessible where classes and instances are accessible. Therefore, strictly speaking, there are no really private or protected attributes in Python (discussed later). We just use these terms analogically to make it easier for programmers from other OOP backgrounds to understand the relevant coding conventions (yes, it's just a convention, not reinforced as real access control).

Let's first discuss how to define the "private" attribute in Python. The convention is to name these attributes with two leading underscores and no more than one underscore. Consider the example of the updated Dog class below-for simplicity, we omitted the other properties defined earlier.

Class Dog:... Def _ _ init__ (self, breed, name):... Self.breed = breed... Self.name = name... Self.__tag = f "{name} | {breed}"... > > dog = Dog ("Rottweiler", "Ada") > dog.name'Ada' > dog.__tagTraceback (most recent call last): File ", line 1, in AttributeError: 'Dog' object has no attribute' _ _ tag'

After the above update, the Dog instance will have a private property named tag, as its name suggests. The instance object can still access its other properties (for example, name) as before. However, the instance cannot access the remaining tags of the private attribute, which may be what we expect. In fact, this restriction on access to these properties is why they are called "private" attributes. But how did it happen, under the hood? After all, as I mentioned earlier, all Python properties are public by default. The following will show you how Python implements the "private" attribute.

> dog.__dict__ {'breed':' Rottweiler', 'name':' Ada','_ Dog__tag': 'Ada | Rottweiler'} > dog._Dog__tag'Ada | Rottweiler'

The _ _ dict__ special method (also known as the dunder method, with a double underscore before and after the name) can display a dictionary representation of the object. Specifically, the key-value pairs in the dictionary are the properties of the object and their values. As we can see, in addition to the bread and name attributes, there is also an attribute called the _ dog__tag tag. This property is exactly how the private property _ _ tag is associated with the object through a process called mangling.

Specifically, mangling or name mangling uses _ ClassName as the prefix for private attributes, so we artificially create access restrictions on these "private" attributes. However, if we do want to retrieve any private attributes, we can still access it with the corrupted name, just as we did with the _ dog__ tag in the code snippet.

5. Protected attribute

In the previous section, we discussed private attributes, but what about protected attributes? the attribute name corresponding to the protected attribute in Python has only an underscore. Unlike double underscores that cause confusion, single underscore prefixes don't change the way the Python interpreter handles these attributes-it's just a convention in the Python programming world that they (for example, encoders) don't want you to access them. However, if you insist on visiting them, you can still do so. Let's look at the following code.

Class Dog:... Def _ _ init__ (self, breed, name):... Self.breed = breed... Self.name = name... Self.__tag = f "{name} | {breed}"... Self._nickname = name [0]

We update the class Dog by creating an instance property named _ nickname. By convention, it is considered a "protected" attribute, as its name is indicated by an underscore prefix. We can still access these protected attributes as other "public" attributes, but some ide or Python editors do not provide hints for these non-public attributes (for example, autocomplete prompts). For examples of using Jupyter notebooks, see the screenshot.

If we use modules instead of classes, as we do here, when we import modules using from _ module import *, names with underlined prefixes will not be imported, providing a mechanism to restrict access to these "protected" attributes.

At this point, I believe you have a deeper understanding of "what are the knowledge points of high-level concept attributes in Python?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report