SoFunction
Updated on 2024-10-30

Explaining Special Members of Python Classes

There are two forms of class members

Publicly owned members, accessible from anywhere

Private members, which can only be method inside the class, are named with the first two characters being underscores.

class Foo:
  def __init__(self, name, age):
     = name
    self.__age = age

  def show(self):      # Indirect method private fields
    return self.__age
  

obj = Foo('klvchen', 25)
print()
res = ()
print(res)

Run results:

klvchen
25

Public static fields: accessible by class; accessible within class; accessible in derived classes

Private static fields: accessible only inside the class;

class Foo:
  __v = '666'     # Private static fields
  def __init__(self):
    pass
  def show(self):
    return Foo.__v
obj = Foo()
res = ()
print(res)

Results.

666

class Foo:
  __v = '666'
  def __init__(self):
    pass
  def show(self):
    return Foo.__v
  @staticmethod
  def stat():
    return Foo.__v
res = ()
print(res)

Results.

666

Unable to inherit private fields from parent class

class F:
  def __init__(self):
     = 123
    self.__gene = 456   # Private fields
class S(F):
  def __init__(self, name):
     = name
    self.__age = 18
    super(S, self).__init__()
  def show(self):
    print()
    print(self.__age)
    print()
    print(self.__gene)
s = S('klvchen')
()

Results.

klvchen
18
123
AttributeError: 'S' object has no attribute '_S__gene'

Special members of a class

int(object), will automatically execute the __int__ method in the object, and will return the assignment to the int object, the same way str(object), will automatically execute the __str__ method, and return the assignment to the str object.

class Foo:
  def __init__(self):
    pass
  def __int__(self):
    return 666
  def __str__(self):
    return 'hello world'
obj = Foo()
print(obj, type(obj))
res = int(obj)
print(res)
res1 = str(obj)
print(res1)

Results.

<__main__.Foo object at 0x0000022BBE9DA978> <class '__main__.Foo'>
666
hello world

print(object), str(object), all automatically execute the __str__ method in the object and return the

class Foo:
  def __init__(self, n, a):
     = n
     = a

  def __str__(self):
    return '%s-%d' %(, )

obj = Foo('klvchen', 28)
print(obj)

Run results:

klvchen-28

When two objects are added together, the __add__ method of the first object is automatically executed and the second object is passed in as a parameter

class Foo:
  def __init__(self, name, age):
     = name
     = age
  def __add__(self, other):
    return  + 
obj1 = Foo('klv1', 23)
obj2 = Foo('klv2', 24)
res = obj1 + obj2
print(res, type(res))

Results.

47 <class 'int'>
class Foo:
    def __init__(self, name, age):
        = name
        = age
    def __add__(self, other):
        return Foo(, )
    def __del__(self):
print('Deconstruction method')
obj1 = Foo('klv1', 23)
obj2 = Foo('klv2', 24)
res = obj1 + obj2
print(res, type(res))

Results.

<__main__.Foo object at 0x0000016DFCE125C0> <class '__main__.Foo'>
destructuring method
destructuring method
destructuring method

li[object] automatically executes the __getitem__ method of the class of the li object, passing 8 as an argument to item

class Foo:
  def __init__(self, name, age):
     = name
     = age
  def __getitem__(self, item):
    return item
li = Foo('klvchen', 28)
r = li[8]
print(r)

Results.

8

The __setitem__,__delitem__ methods in the class

class Foo:
  def __init__(self, name, age):
     = name
     = age
  def __getitem__(self, item):
    return item
  def __setitem__(self, key, value):
    print(key, value)
  def __delitem__(self, key):
    print(key)
li = Foo('klvchen', 28)
r = li[8]
print(r)
li[100] = 'hello'
del li[999]

Results.

8
100 hello
999

Execute the __iter__() method in the class and get its return value, return the object in the previous step of the loop for the iterator, the reason why lists, dictionaries, and tuples can be subject to for loops is because of the internal definition of the type iter

class Foo:
  def __init__(self, name, age):
     = name
     = age
  def __iter__(self):
    return iter([11, 22, 33])
li = Foo('klvchen', 26)
for i in li:
  print(i)

Results.

11
22
33

The inner workings of a for loop

obj = iter([11, 22, 33])
while True:
  val = ()
  print val

summarize

The above is a small introduction to the Python class of special members of the analysis, I hope to help you, if you have any questions please leave me a message, I will promptly reply to you. Here also thank you very much for your support of my website!