Python in Advent Calendar is depopulated, so I'll continue to write some simple material yesterday.
Here is a summary of the scopes of Python class members summarized earlier.
Specifically, how to write and access public members and methods, and how to write and access private members and methods.
# coding: utf-8
class Widget(object):
#constructor
def __init__(self, r, l):
#Normal member variable
self.rval = r
self.lval = l
#Private variables
self.__secret = 5
#public class member variable
classVal = 30
#Private class variables
#It can only be accessed from the outside with a special description
__SecretClassVal = 10
#Normal method
def Calc(self):
#Member variables can be defined here as well.
self.top = 10
return self.rval * self.lval * self.top
#Private method
def __MyCalc(self):
print "This is Private Method!"
#Class method.
@classmethod
def SelfName(cls):
#Class member variables can be defined here as well.
cls.number = 1
#Private class method.
@classmethod
def __PrivateSelfName(cls):
print "This is Private Class Method!"
if __name__ == '__main__':
#Calls to constructors and regular methods.
w = Widget(2, 4)
#Access to member variables
w.lval = 3
w.rval = 4
#Access private member variables.
#instance._name of the class__It can be accessed by variable name.(Not recommended)
print w._Widget__secret
#Access public class variables.
#You can access either the instance name or the class name.
print Widget.classVal
print w.classVal
#Access private class variables.
#instance._name of the class__It can be accessed by variable name.(Not recommended)
print w._Widget__SecretClassVal
#Normal method call.
print w.Calc()
#Calling a private method(Not recommended)
print w._Widget__MyCalc()
#Calling a class method.
Widget.SelfName()
#Calling a private class method(Not recommended)
print w._Widget__PrivateSelfName()
output
5
30
30
10
120
This is Private Method!
None
This is Private Class Method!
None
Recommended Posts