Private Properties and Private Methods for python Fundamentals
- 2021-10-15 10:51:31
- OfStack
Private rights
Three characteristics of object-oriented: encapsulation, inheritance and polymorphism
Significance of encapsulation:
Private permissions: Prefix the property name and method name with two underscores __
Private properties and private methods of a class can not be accessed directly through objects, but can be accessed inside the class; Private properties and private methods of classes will not be inherited by subclasses, and subclasses cannot access them. Private properties and private methods are often used to handle the internal affairs of classes, not through object processing, and play a safe role.Private attribute
"""
Private attribute , Just prefix the original attribute name with two underscores , You can
Purpose : Ensure the relative security of data ,
Want to access and use private properties : Definition 1 A public method , Using this method
"""
# Case requirements : Definition People Class , Defining Attributes ICBC_money , Money can't be modified at will , Must be a legitimate terminal to operate
class People(object):
def __init__(self):
# python The private nature of the Modify the name of the property , When creating an object, , The attribute name is automatically modified
# Prefix the attribute name with _ Class name prefix
self.__ICBC_money = 0 # Define private properties
# Define public methods , Provide an interface , Modify the balance
def get_money(self):
return self.__ICBC_money
def set_money(self, money):
num = input(' Enter Amount :')
self.__ICBC_money += int(num)
# self.__ICBC_money += money
# Create People Class object
xw = People()
# Instance object .__dict__ You can view the attribute information that an object has , Type is a dictionary , Dictionary key Is the property name , Dictionary value Is an attribute value
print(' Before assignment :', xw.__dict__)
# print(xw.__ICBC_money)
xw.__ICBC_money = 1000 # Not modifying private properties , Is re-added 1 Public attribute
print(' After assignment :', xw.__dict__)
print(xw.__ICBC_money)
print('=' * 20)
print(xw.get_money()) # 0
xw.set_money(1000)
print(xw.get_money()) # 1000
xw.set_money(-500)
print(xw.get_money()) # 500
Private method
"""
Private method : Prefix the method with two __ , Is a private method
Private method , Cannot be accessed outside the class
Action : 1 As a method inside the class , Do not let it be called directly from the outside , Ensure that business logic is not destroyed
"""
class Dog(object):
def born(self):
""" The way to give birth to puppies , Health 1 A puppy , Rest 30 Days """
print(' Be born 1 A puppy ...')
self.__sleep()
def __sleep(self):
print(' Rest 30 Days ')
dog = Dog()
# dog.__sleep()
dog.born()