I'm creating an instance called Dog1. I'm curious what's the best practice in referencing objects.
Would I refer them later on in the class by self.breed or just by the object name breed.
For example in the print function below would I put in print(f"My name's {self.name}) or print(f"My name's {name})
class Dog:
def __init__(self, name, age, breed):
self.name = name
self.age = age
self.breed = breed
print(f"My name's {name}")
In later functions, you would refer to your variables as self.name. For example, you could do this:
class Dog:
def __init__(self, name, age, breed):
self.name = name
self.age = age
self.breed = breed
print(f"My name's {self.name}")
def print_breed(self):
print(f"I'm a {self.breed}")
dog = Dog("Fido", 10, "spaniel") # >>> My name's Fido
dog.print_breed() # >>> I'm a spaniel
Here, when you call dog.print_breed(), where dog is a variable instance of the Dog class, you would get back what the dog's breed is.
class Dog:
def __init__(self, name, age, breed):
self.name = name + '-sss-'
self.age = age
self.breed = breed
print(f"My name's {name}")
print(f"My name's {self.name}")
def s(self):
print(self.name)
try:
print(name)
except NameError as e:
print(e)
It depends on what you want. Within the __init__ method {name} will print the value you passed for that argument. {self.name} will print the instance attribute.
In [10]: d = Dog('foo',1,2)
My name's foo
My name's foo-sss-
In instance methods you need to use self.
In [11]: d.s()
foo-sss-
name 'name' is not defined
Related
I am working on a program that needs a str method. However, when I run the code, it only outputs:
What is the name of the pet: Tim
What type of pet is it: Turtle
How old is your pet: 6
How can I print out what I need from the str method?
Here is what I have.
This is the code for my class (classPet.py)
class Pet:
def __init__(self, name, animal_type, age):
self.__name = name
self.__animal_type = animal_type
self.__age = age
def set_name(self, name):
self.__name = name
def set_type(self, animal_type):
self.__animal_type = animal_type
def set_age(self, age):
self.__age = age
def get_name(self):
return self.__name
def get_animal_type(self):
return self.__animal_type
def get_age(self):
return self.__age
def __str__(self):
return 'Pet Name:', self.__name +\
'\nAnimal Type:', self.__animal_type +\
'\nAge:', self.__age
This is the code for my main function (pet.py):
import classPet
def main():
# Prompt user to enter name, type, and age of pet
name = input('What is the name of the pet: ')
animal_type = input('What type of pet is it: ')
age = int(input('How old is your pet: '))
pets = classPet.Pet(name, animal_type, age)
print()
main()
In the code for your main function (pet.py), you are calling print without any parameters. You need to call print with your pet instance as a parameter:
pets = classPet.Pet(name, animal_type, age)
print(pets) # see here
You also need to fix an error in your __str__ method:
the __str__ method doesn't concatenate all of its arguments to a string like the print() function does it. Instead, it must return a single string.
In your __str__ method you are seperating your different parts of the string by commas. This will make python think that it's dealing with a tuple. I propose the following solution using pythons format function:
def __str__(self):
return "Pet Name: {}\nAnimal Type: {}\nAge: {}".format(self.__name, self.__animal_type, self.__age)
The {} parts in the string are placeholders that are replaced with the arguments in the parenthesis through the format function. They are replaced in order, so the first one is replaced with self.__name, etc.
I want to get instance of one of subclasses when trying get instance of a superclass (parent class) depending on arguments. For example, I have parent class(I'm using python3):
class Man:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print("Hello! My name is {}.".format(self.name))
And subclass:
class YoungMan(Man):
def say_hello(self):
print("Hey, man! Wazap?")
If age of Man less 30, I want it become YoungMan:
John = Man('John', 25)
type(John) #<class '__main__.YoungMan'>
John.say_hello() #Hey, man! Wazap?
I tried solve it with Man.__new__():
class Man:
def __new__(cls, name, age):
if age < 30:
return YoungMan(name, age)
else:
return super(Man, cls).__new__()
...
But John.say_hello() returns Hello! My name is John. So Man methods override YoungMan methods. After I tried use metaclass for Man:
class ManFactory(type):
def __call__(self, name, age):
if age < 30:
return YoungMan(name, age)
class Man(metaclass=ManFactory):
...
But it lached on ManFactory.__call__().
I understand that I can use a funtion John = get_Man(name, age) which returns right class, but it isn't so handsome. My question is about how do it like this:
John = Man('John', 25)
type(John) #<class '__main__.YoungMan'>
John.say_hello() #Hey, man! Wazap?
Brad = Man('Brad', 54)
type(Brad) #<class '__main__.Man'>
Brad.say_hello() #Hello! My name is Brad.
Not sure if this is good practice but you could set self.__class__:
class Man:
def __init__(self, name, age):
if age < 30: self.__class__ = YoungMan
self.name = name
self.age = age
def say_hello(self):
print("Hello! My name is {}.".format(self.name))
class YoungMan(Man):
def say_hello(self):
print("Hey, man! Wazap?")
a = Man("Brad", 15)
print(type(a))
>>><class '__main__.YoungMan'>
a.say_hello()
>>>Hey, man! Wazap?
The main problem with this method is that the YoungMan would still be constructed by Man.__init__() so the classes would have to be compatible. Creating a function get_man() is still the best solution.
Hi i have a python file that contains the class pets and a file conatins the class people and a main file
the code is this:
the pets code:
class Pet:
def __init__(self, name, age, sound, type):
self.name = name
self.age = age
self. sound = sound
self. type = type
class Dog(Pet):
def __init__(self, name, age):
super().__init__(name, age, "How How", "Dog")
class Cat(Pet):
def __init__(self, name, age):
super().__init__(name, age, "Mewo", "Cat")
this is the peoples file:
import Pets
class Person:
def __init__(self, gender, name, age):
self.gender = gender
self.name = name
self.age = age
self.pets = []
def addPet(self, pet):
if isinstance(pet, Pets.Pet):
self.pets.append(pet)
else:
print("This is not a pet pls try again.")
def printPets():
print("He has:")
for pet in self.pets:
print("A: " + pet.type+ " Named: " + pet.name)
And this is the Main file:
from Person import Person
import Pets
def Main():
p1 = Person("Male", "Bob", 18)
p1.addPet(Pets.Cat("Mitzi", 2))
p1.addPet(Pets.Dog("Rexi", 5))
print(p1.printPets)
if __name__ == "__main__":
Main()
the output that i get is:
<bound method Person.printPets of <Person.Person object at 0x7f413e3604e0>>
what is this and how do i fix it ??
thanx.
What you need is print(p1.printPets())
You need to invoke the method.
Else what you are doing is printing the method and what Python gives you is the method type (bound), instance type to which it belongs and address of the instance.
You just need to include () inside print() like this:
print(s1.avg())
#C:/Python32
class Person:
def __init__(self, name = "joe" , age= 20 , salary=0):
self.name = name
self.age = age
self.salary = salary
def __printData__(self):
return " My name is {0}, my age is {1} , and my salary is {2}.".format(self.name, self.age, self.salary)
print(Person)
class Employee(Person):
def __init__(self, name, age , salary ):
Person. __init__ (self,name = "Mohamed" , age = 20 , salary = 100000)
def __printData__(self):
return " My name is {0}, my age is {1} , and my salary is {2}.".format(self.name, self.age, self.salary)
print(Employee)
p= Person()
e = Employee()
Your problem can be simplified to:
class Person:
print(Person)
This will raise a NameError. When constructing a class, the body of the class is executed and placed in a special namespace. That namespace is then passed to type which is responsible for actually creating the class.
In your code, you're trying to print(Person) before the class Person has actually been created (at the stage where the body of the class is being executed -- Before it gets passed to type and bound to the class name) which leads to the NameError.
It appears that you want to have your class return certain information when print is called on it, and that you also want that information printed when you create an instance of that class. The way you would do this is to define a __repr__ ( or __str__, for more on that see Difference between __str__ and __repr__ in Python ) method for your class. Then everytime print is called on an instance of your class, it will print what is returned by that __repr__ method. Then you can just add a line to your __init__ method, that prints the instance. Within the class, the current instance is referred to by the special self keyword, the name of the class is only defined outside the scope of the class, in the main namespace. So you should call print(self) and not print(Person). Here's some code for your example:
class Person:
def __init__(self, name = "joe" , age= 20 , salary=0):
self.name = name
self.age = age
self.salary = salary
print(self)
def __repr__(self):
return " My name is {0}, my age is {1} , and my salary is {2}.".format(self.name, self.age, self.salary)
joe = Person()
>>> My name is joe, my age is 20 , and my salary is 0.
I am working on an assignment for Python Programming 157 at my school.
I need to write a class called Pet that has the following data attributes:
__name (for the name of the pet)
__animal_type (Examples: "Cat", "Dog", and "Hamster" )
__age (for the pet's age)
__height (for the pet's height)
It needs to include
set_name
get_name
I have tried like 4 times and cannot seem to get it right... any clues on getting it started?
# The Pet Program.
class PetProgram:
# The __init__ method accepts an argument for the program
# and adds it to the __pets attribute.
def __init__(self, pet):
self.__pets = pet
# The name will add to the pet attribute.
def name(self, name):
self.__pets = name
def age(self, age):
self.__pets = age
def animal(self, animal):
self.__pets = animal
def height(self, height):
self.__pets = height
# The pets_return will show you the list.
def pets_return(self):
return self.__pets
# The Pet Program.
import petsprogram
def main():
# Enter the name.
petname = input('What is the name of the pet: ')
print 'This will be added to the record.'
savings.name(petname)
# Display the list.
print petsprogram
main()
Above is my latest try...no such luck...any help? Thanks in advance...
A class is not a program, a class should model a thing, like a pet. Therefore, to start off, you should name your class appropriately.
class Pet(object): # Pet derives from the object class, always do this
Now I think you want a constructor that takes the name of the pet, and perhaps the type of pet as well, so we'll define that.
def __init__(self, pet_name, pet_type):
self.pet_name = pet_name
self.pet_type = pet_type
You also need a get and set for the name:
def get_name(self):
return self.pet_name
def set_name(self, pet_name):
self.pet_name = pet_name
To use this class, you instantiate it into an instance of the class:
puppy = Pet('Rover', 'Dog')
puppy.get_name() # prints Rover
I hope that's enough to get you going. You should read up on OOP in Python as mentioned in the comments.
First, why are you using "private" __attributes? That doesn't seem warranted.
Second, you're assigning all your properties to the same instance variable:
self.__pets = pet
self.__pets = name
self.__pets = age
self.__pets = animal
self.__pets = height
You should be using something like
def __init__(self, pet, name, age, animal, height):
self.pet = pet
self.name = name
self.age = age
self.animal = animal
self.height = height
and you should definitely read the tutorial on classes before venturing any further.
I'm not sure where the __pets binding comes into play. Your initial description doesn't say anything about that. I would not have expected an object that represents a pet, as in, a singular pet, to have an attribute that was a list of pets. I would expect something like:
class PetProgram:
def __init__(self, name ='', age=0, type='Unknown', height=0):
self.__name = name
self.__age = age
self.__animal_type = type
self.__height = height
def get_name(self):
return self.__name
def set_name(self, name):
self.__name = name
I'm also not sure where the imports petprogram comes from... is that perchance what your supposed to call your module, and then the instructor has provided that as something you're supposed to run to test it?
(also, what's with all the __under_scores? is this something your teacher is encouraging?)
How does something like this look?
>>> class Pets:
def set_Name(self,name):
self.name=name
def get_Name(self):
return self.name
def set_Atype(self,atype):
self.atype=atype
def get_Atype(self):
return self.atype
def set_Age(self,age):
self.age=age
def get_Age(self):
return self.age
def set_Height(self,height):
self.height=height
def get_Height(self):
return self.height