Examples of the method of private / private static methods / private class method --Pytho3

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )

1, private instance methods

Indirect methods can access private instance by non-private instance methods:

# 私有实例方法
class Foo:
    def __init__(self, name):
        self.name = name

    def __f(self):
        print(self.name)

    def getF(self):
        self.__f()

f = Foo('Thanlon')
# f.__f()  # 调用失败
f.getF()
'''
Thanlon
'''
2, private static method

It can be accessed indirectly through private static non-private instance methods instance methods:

# 私有静态方法
class Foo:
    def __init__(self, name):
        self.name = name

    @staticmethod
    def __f():
        print('私有静态方法!')

    def get_f(self):
        self.__f()
        # Foo.__f()
        
# 类.静态方法调用失败
# Foo.__f()
# 通过非私有静态方法
obj = Foo('Thanlon')
obj.get_f()
'''
私有静态方法!
'''

By non-private static method can also be accessed indirectly private static instance method:

# 私有静态方法
class Foo:
    def __init__(self, name):
        self.name = name

    @staticmethod
    def __f():
        print('通过非私有静态方法调用私有静态实例方法!')

    @staticmethod
    def get_f():
        Foo.__f()

# 类.静态方法调用失败
# Foo.__f()

# 类通过调用非私有静态方法间接调用私有静态实例方法!
Foo.get_f()

# 对象通过调用非私有静态方法间接调用私有静态实例方法
obj = Foo('Thanlon')
obj.get_f()
'''
私有静态方法!
'''
3, private class method

You may be accessed indirectly through non-private methods private class instance method:

# 私有类方法
class Foo:
    def __init__(self, name):
        self.name = name

    @classmethod
    def __f(cls):
        print(cls)

    def get_f(self):
        self.__f()
        # Foo.__f()

obj = Foo('Thanlon')
obj.get_f()
'''
<class '__main__.Foo'>
'''

By non-private static method can also indirectly access private class methods:

# 私有类方法
class Foo:
    def __init__(self, name):
        self.name = name

    # 私有静态方法
    @classmethod
    def __f(cls):
        print(cls)

    def get_f(self):
        self.__f()
        # Foo.__f()

    # 静态方法
    @staticmethod
    def reget_f():
        Foo.__f()

# 类调用静态方法reget_f
Foo.reget_f()

# 对象调用静态方法reget_f
obj = Foo('Thanlon')
obj.get_f()

'''
<class '__main__.Foo'>
<class '__main__.Foo'>
'''

Where there are problems writing, but also pointed out that hope, Python learning and communication can add my QQ: 3330447288

Guess you like

Origin blog.csdn.net/Thanlon/article/details/94217947