Home > other >  Just learning python classes and objects, consult the code why not
Just learning python classes and objects, consult the code why not

Time:09-21

The class Person: # define a human
Def __init__ (self, life_value) :
Self. Life_value=https://bbs.csdn.net/topics/life_value

The class Dog:
Def __init__ (self, life_value) :
Self. Life_value=https://bbs.csdn.net/topics/life_value

Def bite (self, life_value) :
# dog can bite, the dog is an object,
# dog bites, then human life value will be according to the damage of the dog
Life_value -=5
An egg=Person (1000)
Ha2=Dog (500)
Ha2. Bite (egg),

Tip: TypeError: unsupported operand type (s) for -=: 'Person' and 'int'


Why do you can
Def bite (self, y) :
# dog can bite, the dog is an object,
# dog bites, then human life value will be according to the damage of the dog
Y.l ife_value -=5


What meaning between the two parameters and adding
How to realize the interaction

CodePudding user response:

Because you are the second y is object, the object has the value of the attribute, and the first life_value not object

CodePudding user response:

The first one to write right

CodePudding user response:

The first piece of code you are will wrap up and the dog, the purpose is to change human instance attribute

Dog bite method in the class just you into the parameter -=5

Without human instance attributes -=5, life_value,

Solution can be the second parameter in the bite into instance objects
 
The class Person:
Def __init__ (self, life_value) :
Self. Life_value=https://bbs.csdn.net/topics/life_value

The class Dog:
Def __init__ (self, life_value) :
Self. Life_value=https://bbs.csdn.net/topics/life_value

Def bite (self, name) :
Name. Life_value -=5
# equivalent in real exception to modify instance attribute

An egg=Person (1000)
Ha2=Dog (500)
Ha2. Bite (egg)

Print (egg. Life_value) # to check the egg life value


Some simplified, easy to understand
 
The class Person () :
Def __init__ (self, life_value) :
Self. Life_value=https://bbs.csdn.net/topics/life_value

An egg=Person (1000)
An egg. Life_value -=5
Print (egg. Life_value)


Can refer to the article: https://mp.weixin.qq.com/s/8Z5QkundsBhdXqI7jFZkXA
  • Related