Python Learning Notes

Posted by Grofit on Sat, 10 Aug 2019 13:09:09 +0200

Python Learning Notes (6)

Object-Oriented Programming (oop)

OOP regards an object as the basic unit of a program. An object contains data and functions to manipulate data.

II. Basic Use

  1. Definition class
class ClassName(object):
    pass
  1. Create an instance
Instance name = ClassName()
  1. Use member attributes or member methods
ClassName. Attribute
 ClassName. Method name ()

3. Member modifiers

Common Attributes: Normal Naming
Private Attributes: Named with two underscores

Fourth, three characteristics of object-oriented

1. Packaging

Encapsulation, as its name implies, is to encapsulate content somewhere and then call the encapsulated content somewhere. For object-oriented encapsulation, in fact, it is to encapsulate the content into the object using construction method, and then obtain the encapsulated content directly or indirectly through the object it self.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def eat(self, food):
        print("Ate{}".format(food))
 
a = Person('jack', 10, 'male')
a.eat()

2. Inheritance

Subclasses inherit parent classes

class Animal:
    def eat(self):
        print "%s eat " %self.name
 
class Cat(Animal):
    def __init__(self, name):
        self.name = name
 
class Dog(Animal):
    def __init__(self, name):
        self.name = name

c1 = Cat('cat')
c1.eat()

d1 = Dog('Dog')
d1.eat()

3. Polymorphism

Python does not support polymorphism, nor does it support polymorphism. Python is a polymorphic language.

class Animal(object):
	def __init__(self, name, age):
		self.name = name
		self.age = age

	def speak(self):
		pass


class Cat(Animal):
	def __init__(self, name, age):
		super().__init__(name, age)

	def speak(self):
		print("cat")


class Dog(Animal):
	def __init__(self, name, age):
		super().__init__(name, age)

	def speak(self):
		print("Wang Wang Wang")


def speak(animal):
	animal.speak()


if __name__ == '__main__':
	dog = Dog("dog", 12)
	cat = Cat("cat", 10)

	speak(dog)
	speak(cat)

V. Various methods

1. Static method

Decorator uses @static method
If no decorator is written, the class name is called intelligently. Method name (), object name can not be used. Method name ()

Call:

  1. Class name. Method name ()
  2. Object name. Method name ()

Feature: Class and member attributes cannot be used

class Person(object):
    def __init__(self, name):
        self.name = name
 
    @staticmethod  # Turn eat method into static method
    def eat(x):
        print("%s is eating" % x)
 
 
d = Person("xiaoming")
d.eat("jack")   

2. Class Method

Decorator uses @class method

Call: Class name. Method name ()

Feature: Only class attributes can be used

class Person(object):
	count = 0

	def __new__(cls, *args, **kwargs):
		cls.count += 1

	@classmethod  # Change eat method into class method
	def show_count(cls):
		print("Created{}Objects".format(cls.count))


d = Person()
Person.show_count()

3. Attribute Method

Decorator

  • Decorated by @ attribute name. setter is the way to set attribute values.
  • The method decorated by @property is the method to get the attribute value, and the name of the decorated method is used as the attribute name.
  • Decorated by @ attribute name. deleter is the way to delete attribute values

Call: Object name. Property name

Feature: By turning a method into a static attribute, attributes are not called in parentheses.

class Person(object):
	def __init__(self, name):
		self.name = name
		self.__age = 0

	@property
	def age(self):
		return self.__age

	@age.setter
	def age(self, age):
		if age > 0 and age <= 100:
			self.__age = age

	@age.deleter
	def age(self):
		print("age Cannot be deleted")


p = Person("Tom")
p.age = 18
print(p.age)
del p.age

4. Magic Method

Function name Effect
__init__(self[, ...]) Constructor, called when initializing a class
__new__(cls[, ...]) 1. The first method to be called when instantiating an object
2. Its parameters are passed directly to _init_ method for processing.
3. We don't usually rewrite this method.
__del__(self) Destruction method, called when instantiated objects are completely destroyed
(Called when all pointers to instantiated objects are destroyed)
__call__(self[, args...]) Allow an instance of a class to be called like a function: x(a, b) calls x.call(a, b)
__str__(self) String representation of classes

Comparison operator

Function name Effect
__lt__(self, other) Define behavior less than sign: x < y calls X. LT (y)
__le__(self, other) Define behavior less than or equal to sign: x <= y calls X. _le_ (y)
__eq__(self, other) Define the behavior of the equals sign: x = y calls X. _eq_ (y)
__ne__(self, other) Define unequal sign behavior: x!= y calls X. _ne_ (y)
__gt__(self, other) Define the behavior of greater than sign: x > y calls X. _gt_ (y)
__ge__(self, other) Define behavior greater than or equal to sign: x >= y calls X. _ge_ (y)

Arithmetic operator

Function name Effect
__add__(self, other) The act of defining addition:+
__sub__(self, other) Define the act of subtraction:-
__mul__(self, other) The act of defining multiplication:*
__truediv__(self, other) Define the act of true division:/
__floordiv__(self, other) The act of defining integer division://
__mod__(self, other) Define the behavior of the modular algorithm:%
__pow__(self, other[, modulo]) Define behavior when invoked by power() or ** operations

Topics: Attribute Python Programming less