python object-oriented programming (class members) II

python object-oriented programming (class members)

table of Contents:

(1) class and instance members

(2) members of the public and private members

(3) Method

 

(A) a member of the class instance members:

Examples of property belonging to the instances (objects), can only be accessed through the object name.

Class attributes belong to the class, or the class name of the object name can be accessed, the data belonging to the class members in the class definition in addition to all methods.

 

class Car:
    price = 1000   #类属性
    def __init__(self,c):
        self.color = c
car1 = Car("red")
car2 = Car("blue")
print(car1.color,car2.color,Car.price)

 D:\anaconda\python.exe D:/untitled/demo.py

red blue 1000

 Process has ended, an exit code of 0

 

(B) members of the public and private member

Private members and member access

 

class Fruit:

    def __init__(self):
        self.__color = 'red'
       
self.price = 2
apple = Fruit()
print(apple.price,apple._Fruit__color)

 

D:\anaconda\python.exe D:/untitled/demo.py

2 red

 Process has ended, an exit code of 0

 

( 1) When members of the class definition, if the member name with two underscores "__" or more to begin with an underscore and not more than two or underline indicates the end of a private member.

(2) private member outside the class is not directly accessible, need to be accessed by members of the public call the object's method. Members of the public can access both within the class may also be used in an external program.

 

The concept underlined

__foo__: Similarly the __init () __ like

_foo: a single underscore represents the beginning of the protected types of variables, namely the protection type can only allow it to itself and the subclass access.

__foo: double underline indicates the type of private (private) variables can only allow access to this class itself.

class Fruit:
    DEF the __init __ (Self):
       Self .__ Color = 'Red' # (own use)
      
self.price = 300
       self._txt = 'WWW' # (with themselves and son)
C = Fruit ()
Print (c._Fruit__color , c.price, c._txt)

 

(C) the classification method

Methods Category:

The method defined in a class can be roughly divided into four categories

Public methods, private methods, static methods, class methods .

Public methods and private methods applied to objects

Public methods: at home this class father, mother, Xiao Ming will be singing, singing this method is public.

Private methods: king of glory only you will play, Mom and Dad will not play, then the king of glory for this approach is that you object to private.

Static method or class method objects and classes can call ( for the class)

 

Guess you like

Origin www.cnblogs.com/abcd8833774477/p/11745702.html