sorry but I just started learning python not too long ago and I'm stuck in thisprogram code, I just can't get it to work like it should.
class Dog():
def __init__(self,name,breed,owner):
self.name = name
self.breed = breed
self.owner = owner
class Person():
def __init__(self,name):
self.name = name
mick = Person("Mick Jagger")
dog = Dog("Stanley","French Bulldog",mick)
print(dog.owner)
I want to get the dog's owner name but all I get is this:
= RESTART: C:/Coding Practice/Object Oriented Programming.py =
<__main__.Person object at 0x000002C5DFB02050>
Help would be appreciated.
You can use __str__ or __repr__ to get all the object's attributes in a more human-readable format.
__str__ (read as "dunder (double-underscore) string") and __repr__ (read as "dunder-repper" (for "representation")) are both special methods that return strings based on the state of the object.
class Dog():
def __init__(self,name,breed,owner):
self.name = name
self.breed = breed
self.owner = owner
def __str__(self):
return str(self.__class__) + '\n'+ '\n'.join(('{} = {}'.format(item, self.__dict__[item]) for item in self.__dict__))
class Person():
def __init__(self,name):
self.name = name
def __str__(self):
return str(self.__class__) + '\n'+ '\n'.join(('{} = {}'.format(item, self.__dict__[item]) for item in self.__dict__))
mick = Person("Mick Jagger")
dog = Dog("Stanley","French Bulldog", mick)
print(dog.owner)
str
If you print an object, or pass it to format, str.format, or str, then
if a str method is defined, that method will be called, otherwise,
repr will be used.
repr
The repr method is called by the builtin function repr and is what
is echoed on your python shell when it evaluates an expression that
returns an object.
when you assign self.owner = owner self.owner stores the reference of owner object you should access the name value by mentioning the attribute self.owner = owner.name.
class Dog():
def __init__(self,name,breed,owner):
self.name = name
self.breed = breed
self.owner_name = owner.name
class Person():
def __init__(self,name):
self.name = name
mick = Person("Mick Jagger")
dog = Dog("Stanley","French Bulldog",mick)
print(dog.owner_name)
You should add __repr__ and __str__ methods to the Person class. Or just __repr__.
class Person:
def __init__(self,name):
self.name=name
def __repr__(self)
return str(self.name)
Related
I want to format an attribute-string of a class with another attribute of the same class like this:
class Test:
def __init__(self):
self.name = None
self.full_name = 'name, {}'.format(self.name)
def print_name(self):
print(self.full_name)
my_object = Test()
my_object.name = 'my_object'
my_object.print_name()
Now it should print 'name, my_object'
But it prints 'name, None'
What to do that the string formats with the assigned value of the object?
You need to add full_name as a property so that you can add some more logic to it:
class Test:
def __init__(self):
self.name = None
#property
def full_name(self):
return f'name, {self.name}'
def print_name(self):
print(self.full_name)
my_object = Test()
my_object.name = 'my_object'
my_object.print_name()
Resources:
property function (built-in)
I have this class and method:
class Person(object):
def __init__(self, name):
self.name = personname
self.surname = personsurname
def changenameorsurname(self, x, y):
self.x = y
return
AdamSmith = Person ("Adam", "Smith")
I want to use method changenameorsurname to change AdamSmith's name or surname, but if I use this code I'm getting a NameError"
AdamSmith.changenameorsurname(personname, Dave)
Result:
NameError: name personname is not defined.
Is there elegant way to reference personname in code like this? Or do I have to make two separate methods like this?
def changename(self, y):
self.name = y
return
AdamSmith.changename(Dave)
There are a couple of problems. Your init method needs to be fixed so you can properly construct a Person object. You can have your changenameorsurname() method take one argument that is a name and a second argument that determines whether that name is the first name or the surname. Here, I have set the default to first name.
class Person:
def __init__(self, first_name, surname):
self.first_name = first_name
self.surname = surname
def changenameorsurname(self, name, first = True):
if first:
self.first_name = name
else:
self.surname = name
def __str__(self):
return f'{self.first_name} {self.surname}'
some_guy = Person ("Adam", "Smith")
print(some_guy) #Adam Smith
some_guy.changenameorsurname("Michael")
print(some_guy) #Michael Smith
some_guy.changenameorsurname("Jones", first=False)
print(some_guy) #Michael Jones
Lets say I have parent class A and child class B like this:
class A:
def __init__(self,name):
self.name = name
def __repr__(self):
return f"My name is: {self.name}"
class B(A):
def __init__(self,name,surname):
super(B,self).__init__(name)
self.name = name
self.surname = surname
def __repr__(self):
return f"My name is: {self.name} {self.surname}"
a = A("Jhon")
b = B("Bon","Boby")
print(a)
print(b)
Is there any way to modify the B.__repr__() without repeating code from parent class and use A.__repr__() to just append the surname to its value?
Solution that seems to work is to call super(B,self).__repr__() within B's __repr__() like this:
class A:
def __init__(self,name):
self.name = name
def __repr__(self):
return f"My name is: {self.name}"
class B(A):
def __init__(self,name,surname):
super(B,self).__init__(name)
self.name = name
self.surname = surname
def __repr__(self):
s = super(B,self).__repr__()
s += f" {self.surname}"
return s
a = A("Jhon")
b = B("Bon","Boby")
print(a)
print(b)
Im new to oop with python. Why am I getting this error? Shouldnt it print tom and 12?
class Dog:
def __init__(self,name,age):
self.name = name
self.age = age
def name(self):
return self.name
def age(self):
return self.age
dog = Dog("tom", 12)
print(dog.name())
print(dog.age())
Instance attributes take precedence over class attributes when one of each exists and they have the same name. If you are going to have a method that returns the value of an attribute, a common convention is to make the name of the instance attribute a "private" version of the method name by prefixing an underscore to the name.
class Dog:
def __init__(self, name, age):
self._name = name
self._age = age
def name(self):
return self._name
def age(self):
return self._age
However, until you have a good reason to hide the attribute behind a getter, just expose the attribute as part of the public interface.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
d = Dog("tom", 12)
print(dog.name)
If you later decide to hide the attribute behind a getter and/or setter, you can use a property to do so without changing the public interface.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
#property
def name(self):
return self._name
#name.setter
def name(self, v):
self._name = v
d = Dog("tom", 12)
print(dog.name) # Works the same as before
name is a variable and name is also a function.
Therefore this error.
Just do print(self.name)
you have to create class and change the name of funtion like this
class Dog:
def __init__(self,name,age):
self.name = name
self.age = age
def Name(self):
return self.name
def age(self):
return self.age
dog = Dog("tom", 12)
print(dog.name())
print(dog.age())
I have defined a simple class.
class Person:
age = 0
name = ''
def __init__(self,personAge,personName):
self.age = personAge
self.name= personName
def __str__(self):
return self.name
d = Person(24,'ram')
print(d)
so o/p is coming like this <__main__.Person object at 0x0000020256652CF8> .But i want o/p like this ram. How can i get this?
please be correcting me.Thnaks in adavance
your indentation is wrong. Your overrided str inside init (constructor). Also you don't have to specify class variables if you are getting/initialising the variables through constrcutor.
try below,
`
class Person:
def __init__(self,personAge,personName):
self.age = personAge
self.name= personName
def __str__(self):
return self.name
d = Person(24,'ram')
print(d)
`
You are printing the class object, not return value of the method (see last line here). Possible indentation issue for __str__() method fixed, too.
class Person:
age = 0
name = ''
def __init__(self,personAge,personName):
self.age = personAge
self.name= personName
def __str__(self):
return self.name
d = Person(24,'ram')
print(d.__str__())
See also PEP 8 for naming conventions.
class Person:
age = 0
name = ''
def __init__(self, personAge, personName):
self.age = personAge
self.name= personName
def __str__(self):
return self.name
d = Person(24,'ram')
print(d)
__str__ should be out of __init__ scope