The other day I learned about 100 Days Of Code, which was popular on Twitter for a while. The purpose of this article is to keep a record and output how much I, as a beginner, can grow through 100 days of study. I think there are many mistakes and difficult to read. I would appreciate it if you could point out!
--Chapter 8 structure --Page 216 of this chapter
--Progress: Pages 79-86 --Chapter 3: Classes and Inheritance ――I will write down what I often forget or didn't know about what I learned today.
There are public and private visibility of attributes in Python classes. It is treated as private by adding two underscores. ** Only those declared inside the class block can be accessed privately. ** ** For example, subclasses cannot access the parent class's private.
class MyObject(object):
def __init__(self):
#public
self.public_field = 2
#private
self.__private_field = 4
def get_private_field(self):
return self.__private_field
The public can be accessed from anywhere with the dot operator.
obj = MyObject()
print(obj.public_field)
# 2
Private throws an exception when trying to access it with the. Operator.
print(obj.__private_field)
Output result
AttributeError: 'MyObject' object has no attribute '__private_field'
Let's check the attributes of the object using __dict__
.
print(obj.__dict__)
# {'public_field': 2, '_MyObject__private_field': 4}
Public has the same attribute name, but private is _MyObject__private_field
instead of __private_field
.
In Python, the behavior of private attributes is done by simple conversion of attribute names.
Therefore, you can easily access your private life by doing the following.
print(obj._MyObject__private_field)
# 4
However, even with this method, the parent's private class is not accessible. In the first place, Python's private is not excluded from subclasses because it can be accessed from the outside by force and it becomes inaccessible when it becomes multiple inheritance. Internal APIs and attributes should be taken into account and protected fields should be described in the documentation. It seems that private use should only be considered when avoiding name conflicts with subclasses.
Many methods are required to successfully implement a custom container type. Therefore, it is quite difficult to define your own container type. The module that exists to eliminate them is collections.abc. This module defines an abstract base class that provides all the typical container-type methods. The module will point out that you have created this abstract base class and forgot to implement the required methods.
from collections.abc import Sequence
class BadType(Sequence):
pass
foo = BadType()
# TypeError: Can't instantiate abstract class BadType with abstract methods __getitem__, __len__
Recommended Posts