Understanding and application of attributes in python

Posted by freeak08 on Tue, 25 Jan 2022 13:36:27 +0100

1, Built in properties

Using the built-in function dir, you can view all the properties and methods supported by an object. There are many built-in properties in Python.

__slots__

Python supports dynamic attributes. You can directly add attributes to an object through point syntax. The code is more flexible. However, in some cases, we may need to control the attribute. In this case, we can use__ slots__ realization.

class Person(object):
    __slots__ = ('name', 'age')
    def __init__(self, name, age):
        self.name = name
        self.age = age
p = Person('Zhang San', 18)
p.name = 'Li Si'

# Object p can only set the name and age attributes, and cannot add attributes dynamically
# p.height = 180 # report errors

__doc__

Represents the description of the class.

class Foo:
    """ Describe class information, which is a magic tool for watching movies """
    def func(self):
        pass

print(Foo.__doc__)
#Output: class description information

__ module__ And__ class__

__ module__ Indicates which module the object of the current operation is in__ class__ What class represents the object of the current operation.

test.py
class Person(object):
    def __init__(self):
        self.name = 'laowang'
main.py
from test import Person

obj = Person()
print(obj.__module__)  # Output test: output module
print(obj.__class__)  # Output test Person: output class

__dict__

Displays all properties and methods of the object in the form of a dictionary.

class Province(object):
    country = 'China'

    def __init__(self, name, count):
        self.name = name
        self.count = count

    def func(self, *args, **kwargs):
        print('func')

# Get the properties of the class, i.e. class properties, methods
print(Province.__dict__)
# Output: {\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\at0x1018978c8 >}

obj1 = Province('Shandong', 10000)
print(obj1.__dict__)
# Get the properties of object obj1
# Output: {'count': 10000, 'name': 'Shandong'}

obj2 = Province('Shanxi', 20000)
print(obj2.__dict__)
# Get the properties of object obj1
# Output: {'count': 20000, 'name': 'Shanxi'}

__ getitem_,__ setitem__ And__ delitem__ method

These three methods are to operate the object as a dictionary.

class Foo(object):

    def __getitem__(self, key):
        print('__getitem__', key)

    def __setitem__(self, key, value):
        print('__setitem__', key, value)

    def __delitem__(self, key):
        print('__delitem__', key)

obj = Foo()

result = obj['k1']      # Automatic trigger execution__ getitem__
obj['k2'] = 'laowang'   # Automatic trigger execution__ setitem__
del obj['k1']           # Automatic trigger execution__ delitem__

 

2, Instance attribute, class attribute

In object-oriented development, the instance created by using class is an object, so is the class an object?

Instance properties

Objects created through classes are called instance objects, and object attributes are also called instance attributes. They record their own data. For instance attributes with the same name of different objects, the recorded data are independent and do not interfere with each other.

class Person(object):
    def __init__(self,name,age):
        # The name and age here belong to instance properties. Each instance has its own properties when it is created
        self.name = name
        self.age = age

# Each time an object is created, the object has its own name and age attributes
p1 = Person('Zhang San',18)
p2 = Person("Li Si",20)

Class properties

Class attribute is the attribute owned by class object, which is shared by all instance objects of the class. Class attribute can be accessed through class object or instance object.

class Dog:
    type = "dog"  # Class properties

dog1 = Dog()
dog2 = Dog()

# The type attribute can be accessed by dog1, dog2 or Dog classes
print(Dog.type)  # Result: dog
print(dog1.type)  # Result: dog
print(dog2.type)  # Result: dog

Usage scenario:

  1. Class attributes are defined when the data recorded by an instance of the class is always consistent.
  2. The instance attribute requires each object to open up a separate memory space for recording data, while the class attribute is shared by the whole class, occupying only one memory, which saves more memory space.

Note:

1. Try to avoid class properties and instance properties with the same name. If there is an instance property with the same name, the instance object will access the instance property first.

class Dog(object):
    type = "dog"  # Class properties

    def __init__(self):
        self.type = "dog"  # Object properties

# create object
dog1 = Dog()

print(dog1.type)     # The result is that the "dog" class attribute has the same name as the instance attribute. The instance object is used to access the instance attribute

2. Class properties can only be modified through class objects, not instance objects

lass Dog(object):
    type = "dog"  # Class properties

# create object
dog1 = Dog()
dog1.type = "dog"   # The object attribute type is created using the instance object

print(dog1.type)     # The result is that the "dog" class attribute has the same name as the instance attribute, and the instance attribute is accessed
print(Dog.type)      # The result is "dog" access class properties

# Class properties can only be modified by using the class name
Dog.type = "Earth dog"
print(Dog.type)  # Earth dog
dog2 = Dog()
print(dog2.type)  # Earth dog

3. Class properties can also be set to private, with two underscores in front. For example:

class Dog(object):
    count = 0  # Public class properties
    __type = "dog"  # Private class properties

print(Dog.count)       # correct
print(Dog.__type)      # Error, private property, external inaccessible.

3, Private properties and methods

In actual development, some properties or methods of an object may only be used inside the object, but not accessed outside. At this time, private properties and methods can be defined.

Definition method

When defining an attribute or method, add two underscores _ before the attribute or method name, What is defined is a private property or method.

class Person:
    def __init__(self,name,age):
        self.name = name
        self.age = age
        self.__money = 2000  # Use__ A modified attribute is a private attribute

    def __shopping(self, cost):
        self.__money -= cost  # __ money can only be used inside objects
        print('Remaining%d element'%self.__money)

    def test(self):
        self.__shopping(200)  # __ The shopping method can only be used inside the object

p = Person('Zhang San',18)
# Print (P.)
p.test()
# p.__shopping() will report an error here__ shopping can only be used inside the object and cannot be accessed externally

Access private properties and methods

Private properties cannot be used directly, and private methods cannot be called directly. However, through some code, we can also access the private properties and methods of an object externally.

Direct access

Usage: add before private property name or method name_ Class name

class Person:
    def __init__(self,name,age):
        self.name = name
        self.age = age
        self.__money = 2000

    def __shopping(self, cost):
        self.__money -= cost


p = Person('Li Si',20)
print(p._Person__money)  # Use object name_ Class name__ The private property name can directly access the private property of the object
p._Person__shopping(100)  # Use object name_ Class name__ The function name can directly call the private method of the object
print(p._Person__money)

Note: the use of} object names is strongly discouraged in development_ Class name__ Private property name {to access the private property of the object!

Define methods to access private variables

In actual development, if the variable of the object is used__ To modify, it means that it is a private variable, and it is not recommended to use and modify it directly from the outside. If you have to modify this property, you can define get and set methods.

class Person:
    def __init__(self,name,age):
        self.name = name
        self.age = age
        self.__money = 2000  # __ money is a private variable and cannot be accessed externally

    def get_money(self):  # Get defined_ Money method, in which you get__ money
        return self.__money  # Internal access__ money variable

    def set_money(self,money): # Set defined_ Money method, in which you can modify__ money
        self.__money = money

p = Person('Wang Wu',21)

# External call get_money and set_money these two public methods get and modify private variables
print(p.get_money())
p.set_money(8000)
print(p.get_money())

 

Topics: Python