I decided to study python's OOP on my own. In the "car" class, I create the "carHP" function, then I want to write the result of this function to the "power" variable, but the compiler throws an error. What could be the problem? I wrote it without class, everything works, but then the meaning of OOP is lost
class car():
nameCar=""
def carHP(self):
if self.nameCar=="BMW":
HP=666
return HP
power=carHP()
def infoCar(self):
print("You owner: ", self.nameCar)
print("HP car: ", self.power )
class person():
namePerson=""
def infoPerson(self):
print("Ваше имя: ",self.namePerson)
person1=person()
person1.namePerson=input("Enter your name: ")
car1=car()
car1.nameCar=input("Enter car name: ")
person1.infoPerson()
car1.infoCar()
CodePudding user response:
you need to know the basics of python oop because you are using class variable instead of instance variables, do your research about the difference of both and simplify the logic
here is a better way for you to start
class Car:
def __init__(self, car_name, car_hp=100):
self.car_name = car_name
self.car_hp = car_hp
class Person:
def __init__(self, person_name):
self.person_name = person_name
def person_info(self):
print(f"Person Name: {self.person_name}")
CodePudding user response:
I found some things to work on my end with a few tweaks on your code. Check them out...
I noticed how you have not called the function carHP() which may be important at initializing HP car: to 666
person1=person()
person1.namePerson=input("Enter your name: ")
car1=car()
car1.nameCar=input("Enter car name: ")
person1.infoPerson()
car1.infoCar()
Secondly, inheritance inside a class method do not receive instances automatically. They require the self. parameter to receive the contents of the method it came from. otherwise, you are returning an instance of that variable but without its parent method
I apologies if that does not make sense. But please have a look at https://docs.python.org/3/tutorial/classes.html for more information.
With the self parameter added and function called to be a conditional statement we get the following output...
class car:
nameCar = ""
power = None
def carHP(self):
if self.nameCar == "BMW":
HP = 666
self.power = HP # notice this change
def infoCar(self):
print("You owner: ", self.nameCar)
print("HP car: ", self.power)
class person():
namePerson = ""
def infoPerson(self):
print("Ваше имя: ", self.namePerson)
person1 = person()
person1.namePerson = input(str("Enter your name: "))
car1 = car()
car1.nameCar = input(str("Enter car name: "))
car1.carHP() # notice this change
person1.infoPerson()
car1.infoCar()
Output:
Enter your name: Name
Enter car name: BMW
Ваше имя: Name
You owner: BMW
HP car: 666
Process finished with exit code 0