This question already has answers here:
How can I choose a custom string representation for a class itself (not instances of the class)?
(7 answers)
Closed 11 months ago.
im trying to make it so the code prints out the random roles and the random name but when i run the code it gives <main.players object at 0x7f7b87db0bb0> get the <main.items object at 0x7f7b87dbf3d0> this response
i tried to add .name to the print but it would say that they have no attributes
i want it to print out the random item and roles name
import random
class players:
def __init__ (self, role, inkey):
self.name = role
self.key=inkey
class items:
def __init__ (self, name):
self.itemname = name
self.owner=""
Roles=[["Hacker","Q"],["Lookout","P"],["Money Man","Z"],["Explosive expert","M"]]
objectroles=[]
for i in Roles:
object1 = players(i[0],i[1])
objectroles.append(object1)
Items=["Goggles","Headset","Torch","Explosives","Map","Laptop","Gloves","Drill"]
objectitems = []
for i in Items:
object2 = items(i)
objectitems.append(object2)
templist=[]
def get():
global templist
item1=random.choice(objectitems)
role1=random.choice(objectroles)
print(role1,"get the", item1)
templist.append(item1)
get()
def take():
global templist
item1=random.choice(objectitems)
role1=random.choice(objectroles)
print(role1,"take the", item1)
templist.append(item1)
take()
Add __str__ methods to your classes to change the way that they're printed:
class players:
def __init__ (self, role, inkey):
self.name = role
self.key=inkey
def __str__(self):
return self.name
class items:
def __init__ (self, name):
self.itemname = name
self.owner=""
def __str__(self):
return self.itemname
Related
This question already has answers here:
Type annotation for classmethod returning instance
(2 answers)
Python: type-hinting a classmethod that returns an instance of the class, for a class that is inherited
(2 answers)
Closed 8 months ago.
I have a parent class with a method that returns an instance of that class.
This class has one (or several) children classes.
How to provide type hints to indicate that the method call on any child class will return an instance of that very child class and not the parent class?
For example, with the following code:
from random import randint
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
#classmethod
def get_random_person(cls) -> "Person":
return cls("Random Guy", randint(18, 65))
class Player(Person):
pass
def welcome_player(player: Player):
print(f"Welcome {player.name}")
player = Player.get_random_person()
welcome_player(player)
The linter mypy would raise an error:
error: Argument 1 to "welcome_player" has incompatible type "Person"; expected "Player"
Found 1 error in 1 file (checked 1 source file)
Of course, you could do something like the following, but that is very heavy if the parent class is inherited multiple times:
from random import randint
from typing import cast
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
#classmethod
def get_random_person(cls) -> "Person":
return cls("Random Guy", randint(18, 65))
class Player(Person):
#classmethod
def get_random_person(cls) -> "Player":
return cast(Player, super().get_random_person())
def welcome_player(player: Player):
print(f"Welcome {player.name}")
player = Player.get_random_person()
welcome_player(player)
Any suggestion on a smart way to achieve that?
You can use typing.TypeVar with parameter bound to simulate:
from random import randint
from typing import TypeVar, Type
Self = TypeVar('Self', bound='Person')
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
#classmethod
def get_random_person(cls: Type[Self]) -> Self:
return cls("Random Guy", randint(18, 65))
class Player(Person):
pass
def welcome_player(player: Player):
print(f"Welcome {player.name}")
player: Player = Player.get_random_person()
welcome_player(player)
Python 3.11 will add the Self type, but it has not been officially released yet. This is accessible in older versions with the typing-extensions, although mypy will complain that error: Variable "typing_extensions.Self" is not valid as a type).
from random import randint
from typing_extensions import Self
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
#classmethod
def get_random_person(cls) -> Self:
return cls("Random Guy", randint(18, 65))
class Player(Person):
pass
def welcome_player(player: Player):
print(f"Welcome {player.name}")
player = Player.get_random_person()
welcome_player(player)
This question already has answers here:
How to print instances of a class using print()?
(12 answers)
Closed 11 months ago.
Suppose I have this class set up
class X:
def __init__(self, name):
self.name = name
self.friends = []
def addFriend(self, name):
self.friends.append(name)
def getFriends(self):
return self.friends
joe = X('joe')
tom = X('tom')
joe.addFriend(tom)
joe.getFriends()
When I call joe.getFriends() I'm expecting to get [tom]. Instead I'm getting the following
[<__main__.X at 0x25eb81187f0>]
I think I'm missing something really simple so I need some pointers in the right direction. Thanks.
To specify how your class instance is represented, define the __repr__ method:
class X:
def __init__(self, name):
self.name = name
self.friends = []
def addFriend(self, name):
self.friends.append(name)
def getFriends(self):
return self.friends
def __repr__(self):
return self.name
joe = X('joe')
tom = X('tom')
joe.addFriend(tom)
joe.getFriends()
Output:
[tom]
This also works for print:
print(tom)
Output:
tom
This question already has an answer here:
Subclass - Arguments From Superclass
(1 answer)
Closed 1 year ago.
Practising Inheritence in python
I am practising inheritance on python. I am unsure how to change the variable name of the parent class.
# Parent Class
class Family_Member():
def __init__(self, name):
self.name = name
def catch_phrase(self):
print("I am a family member")
# Child Class
class Mum(Family_Member):
def __init__(self):
Family_Member.__init__(self)
# Attempting to change variable of parent class from child class
My_Mum = Mum("Kerry")
This gives me
TypeError: __init__() takes 1 positional argument but 2 were given
Questions
Why does this occur? How do I name my member Kerry without this error
Why does this error not occur when I don't include the init function in the child class. e.g this code works
# Attempt 2
class Family_Member():
def __init__(self, name):
self.name = name
def catch_phrase(self):
print("I am a family member")
class Mum(Family_Member): # THIS CLASS IS NOW EMPTY
pass
My_Mum = Mum("Kerry")
print(My_Mum.name)
class Family_Member():
def __init__(self, name):
self.name = name
def catch_phrase(self):
print("I am a family member")
class Mum(Family_Member):
def __init__(self, name):
Family_Member.__init__(self, name)
My_Mum = Mum("Kerry")
should work, does it?
I have the following code:
class Person:
def __init__(self,name):
self.name = name
self.balance = 0
def setBalance(self, value):
self.balance = vale
def setName(self, name):
self.name = name
class Main:
def __init__(self):
self.people = []
def addPerson(self,name):
self.people.append(Person(name))
def updateBalance(self,balance,index):
self.people[index].setBalance(50)
print self.people[0]
main = Main()
main.addPerson("Jack")
main.updateBalance(30,0)
I made the following code just to see how objects works with array. But, when I try to run it I get NameError: name 'self' is not defined. I'm not sure what I'm doing wrong ?
If something is not clear or needs editing then please let me know in the comments before down voting.
Many thanks
There a several issues with your code:
Class methods, need to refer to the class def ...(self, ...)
print(...) is a function in Python3 and has to be called from within a method.
The following adjustments make your code work:
class Person:
def __init__(self, name):
self.name = name
self.balance = 0
def setBalance(self, value):
self.balance = value
def setName(self, name):
self.name = name
class Main:
def __init__(self):
self.people = []
def addPerson(self, name):
self.people.append(Person(name))
def updateBalance(self, balance, index):
self.people[index].setBalance(50)
print("Updating people at index %d" % index)
main = Main()
main.addPerson("Jack")
main.updateBalance(30, 0)
print (main.people[0])
Prints:
Updating people at index 0
<__main__.Person instance at 0x100d065f0>
You should pass self as a parameter as well:
class Main:
def __init__(self):
self.people = []
def addPerson(self, name):
self.people.append(Person(name))
def updateBalance(self, balance,index):
self.people[index].setBalance(50)
print people[0] #no need for self if you are calling local variable of class but this will print an empty array
Also you have type error
class Person:
def __init__(self,name):
self.name = name
self.balance = 0
def setBalance(self, value):
self.balance = vale --> not vale but value
def setName(self, name):
self.name = name
Whereas languages like Java or C++ make the "self"/"this" argument implicit in their method definitions, Python makes it explicit. So, the method definitions in your Main class should look like this:
class Main:
def __init__(self):
self.people = []
def addPerson(self, name):
self.people.append(Person(name))
def updateBalance(self, balance, index):
self.people[index].setBalance(50)
In effect, what you had before was an addPerson() method that accepted zero arguments from the caller... and it had renamed self to name, quite unintuitively. Calling the first parameter to a method "self" in Python is only by convention... you could just as easily define addPerson() like this:
class Main:
def addPerson(something_other_t_self, name):
something_other_than_self.people.append(Person(name))
...and it would work exactly the same.
I have a class Participant as follows:
class Participant:
def __init__(self,name,level):
self.name = name
self.level =level
I also have another class Team as follows:
class Team:
def __init__(self,name):
self.name = name
I want to create a method in the class Team to add an instance of class Participant; for instance:
Assume myTeam is an empty, valid instance of Team.
Also assume myParticipant1 is a valid instances of Participant
myTeam.addParticipant(participant= myParticipant1)
AddParticipant method should add the instance myParticipant1 to the instance myTeam.
How do I acheive it in Python?
Aside from the inheritance questions we're talking about in the comments, this is pretty simple stuff.
class Participant(object):
def __init__(self, name, level):
self.name = name
self.level = level
class Team(object):
def __init__(self, name):
self.name = name
self.participants = []
def add_participant(p):
self.participants.append(p)
DEMO:
my_team = Team("Monty Python")
p_info = [("Adam", 10e5), ("Joe-bob", -1)]
participants = [Participant(name, level) for name, level in p_info]
for participant in participants:
my_team.add_participant(participant)
# say that 10 times fast....
In [1]: [p.name for p in my_team.participants]
Out[1]: ["Adam", "Joe-bob"]