Seven Python questions to improve literacy

WBOY
Release: 2023-04-11 16:52:03
forward
1770 people have browsed it

I have gained something from these 7 questions, which are summarized as follows:

1. Reflective arithmetic operators

You may know the magic functions in Python, such as __add__​ and __sub__​ Represents the - operator, which represents obj /- something, but you may not know that there is also a __radd__, __rsub__ function, which can represent something /- obj.

For example:

class Dog:
def __add__(self, other):
return "from __add__"
def __radd__(self, other):
return "from __radd__"
dog = Dog()
print(dog + 1) # from __add__
print(1 + dog) # from __radd__
Copy after login

2. __getattr__ vs __getattribute__

__getattr__​ The magic method will only be called when we try to get an attribute that does not exist, __getattribute__ will be called every time This is called every time we try to access a property.

The code is as follows:

class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def __getattr__(self, key):
return f"{key} not found"
dog = Dog("taidi", 5)
print(dog.name)# taidi
print(dog.age) # 5
print(dog.breed) # breed not found
Copy after login
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def __getattribute__(self, key):
return f"{key} not found"
dog = Dog("taidi", 5)
print(dog.name)# name not found
print(dog.age) # age not found
print(dog.breed) # breed not found
Copy after login

3. Another way of writing super().__init__()

class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
class Dog(Animal):
def __init__(self, name, age, breed):
super().__init__(name, age)
self.breed = breed
Copy after login

is equivalent to:

class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
class Dog(Animal):
def __init__(self, name, age, breed):
Animal.__init__(self, name, age)
self.breed = breed
Copy after login

Please note , Animal.__init__(self, name, age) cannot be missing the self parameter.

4. Method of checking subclasses

class Animal: pass
class Dog(Animal): pass
class Cat(Animal): pass
class GermanSheperd(Dog): pass
print(Animal.__subclasses__())
# [<class '__main__.Dog'>, <class '__main__.Cat'>]
Copy after login

However, .__subclasses__() can only check direct subclasses.

5. When using multiple integrations, which function with the same name should be used by the subclass?

class A:
def test(self):
print("A")
class B:
def test(self):
print("B")
class C(A, B):
pass

C().test() # A
Copy after login

A and B both have test methods, so which one does C integrate? In Python, the leftmost class takes precedence.

Here, A is the leftmost parent class, so A's test method is integrated.

Multiple recharges are confusing, so it’s better not to use them.

6 __invert__ magic function

class Dog:
def __invert__(self):
return "test"
dog = Dog()
print(~dog) # test
Copy after login

~ The operator stands for "bitwise not" and is usually used to invert content. A more meaningful example is as follows:

class Coordinate:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"({self.x}, {self.y})"
def __invert__(self):
return Coordinate(-self.x, -self.y)
a = Coordinate(3, 4)
b = ~a
print(a, b) # (3, 4) (-3, -4)
Copy after login

7. Create a class without using class

def init(self, name, age):
self.name = name
self.age = age
def bark(self):
print("woof")
Dog = type("Dog", (), {"__init__":init, "bark":bark})


dog = Dog("taidi", 10)
print(dog.name)
print(dog.age)

# taidi
# 10
Copy after login

Here, we pass 3 parameters to type to create our class.

The first parameter __name__​ is the name of the class. The second parameter __bases__​ is a tuple containing the parent class. The third parameter __dict__ is a dictionary containing attributes and methods.

Equivalent to:

class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print("woof")
Copy after login

The above is the detailed content of Seven Python questions to improve literacy. For more information, please follow other related articles on the PHP Chinese website!

source:51cto.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!