I want to randomly pick a weapon and i want to write the name of it but the result is not like i expect what is wrong in that code?
import random
class Dusman:
def __init__(self,name='',weapon='',armor=''):
self.name= name
self.weapon= weapon
self.armor= armor
def name(self):
a=name
a = input("Write a name: ")
def weapon(self):
weapon=["Sword","Axe","Topuz"]
print(random.choice(weapon))
def print(self):
print("Name",self.name,"Weapon: ",self.weapon,"Armor: ",self.armor)
dusman1=Dusman()
dusman1.name
dusman1.weapon
dusman1.print()
Is this your expected result?
import random
class Dusman:
def __init__(self,name='',weapon='',armor=''):
self._name= name
self._weapon= weapon
self._armor= armor
def name(self):
self._name = input("Write a name: ")
def weapon(self):
weapons=["Sword","Axe","Topuz"]
self._weapon = random.choice(weapons)
print(self._weapon)
def __str__(self):
return "Name: {0} Weapon: {1} Armor: {2}".format(self._name,
self._weapon,
self._armor)
if __name__ == '__main__':
dusman1=Dusman()
dusman1.name()
dusman1.weapon()
print(dusman1)
Your problem is, that you have naming collisions. You are naming a variable the same as a function.
Currently, you only print the choice.
You need to set the result of the choice to the weapon instance variable:
def weapon(self):
weapons = ["Sword", "Axe", "Topuz"]
self.weapon = random.choice(weapons)
Related
class Satellite:
def __init__(self, message):
print(message)
self.name = input("name: ").title()
self.lbs = int(input("lbs: "))
self.speed = int(input("speed: "))
lstSat = []
e= input("Would you like to create satellites? If yes, type O. If not, type another letter: ").lower()
i=0
while e=="o":
lstSat.append(Satellite("Info for satellite "+str(i+1)))
i+=1
e= input("Type O to create another satellite: ").lower()
Hello,
How can I make sure that 2 Satellites cannot be the same?
Please don't ask for user input during class construction. Much better to acquire the values elsewhere then use a straightforward constructor based on the user's input values.
In order to determine repetition, you need to override the eq dunder method.
Try this:
class Satellite:
def __init__(self, name, lbs, speed):
self._name = name
self._lbs = lbs
self._speed = speed
def __eq__(self, other):
if isinstance(other, str):
return self._name == name
if isinstance(other, type(self)):
return self._name == other._name
return False
def __str__(self):
return f'Name={self._name}, lbs={self._lbs} speed={self._speed}'
lstSat = []
PROMPT = 'Would you like to create satellites? If yes, type O. If not, type another letter: '
while input(PROMPT) in 'Oo':
name = input('Name: ').title()
if name in lstSat:
print(f'{name} already in use')
else:
lbs = int(input('lbs: '))
speed = int(input('Speed: '))
lstSat.append(Satellite(name, lbs, speed))
for satellite in lstSat:
print(satellite)
I would go for iteration in list and check names with every satellite
...
while e=="o":
satellite = Satellite("Info for satellite " + str(i+1))
if check_reapeated_name(lstSat, satellite.name): # see definition of function bellow
lstSat.append(satellite)
else:
# here do some output or error handling
...
...
and the definition of check_reapeated_name() would be something like this:
def check_reapeated_name(lstSat, satellite_name):
for i in lstSat:
if i.name == satellite_name:
return False
return True
I am making a game in python. I ran into some issues with the code. I defined my mobs as different classes, making it easy to edit later on. The issues I ran into is that I cannot call upon the health to deal damage on it.
class spaceStalker(object):
def __init__(self, name, hp):
self.name = name
self.hp = hp
mobList = [spaceStalker]
mob = random.choice(mobList)
killList = ["not killed the beast!", "killed the beast!"]
kill = random.choice(killList)
def game():
if mob == spaceStalker:
fleeAtt = input("A Space Stalker has appeared! Attack or flee? ")
if fleeAtt == "Attack":
hitPass = input("Attack or Pass? ")
if hitPass == "Attack":
spaceStalker.hp -= 50
print(spaceStalker.hp)
else:
print("1")```
Use an instance of the class
mobList = [SpaceStalker('some name', 54)]
And when you do the type of mob checking, you can do it with isinstance(object, classname) :
so instead of:
if mob == spaceStalker:
#dosomething
use:
if isinstance(mob, SpaceStalker):
#dosomething
I also suggest you to use getters and setters for your class:
class SpaceStalker(object):
def __init__(self, name, hp):
self.name = name
self.hp = hp
#property
def hp(self):
return self.__hp
#hp.setter
def hp(self, hp):
#some validation here
self.__hp = hp
Also, maybe you want to use the classname convention (camelcase) so I've written it as SpaceStalker
I'm new to coding -- taking a Python college course. I know this will be obvious to many of you, but I can not figure out why I continue to get this error attribute error:
prodworker = employee.ProductionWorker(shift_num, pay_rate)
AttributeError: 'Employee' object has no attribute 'ProductionWorker'
Any help is greatly appreciated :)
class Employee: #writing new class called Employee:
def __init__(self, name, number): #accepts arguments for employee name and
self.__name = name #employee number
self.__number = number
def set_name(self, name): #mutator methods to set name and number
self.__name = name
def set_number(self, number):
self.__number = number
#accessor methods returns name and number
def get_name(self):
return self.__name
def get_number(self):
return self.__number
class ProductionWorker(Employee): #write subclass
def __init__(self, shift_num, pay_rate):
Employee.__init__(self, 'ProductionWorker')
self.__shift_num = shift_num
self.__pay_rate = pay_rate
def set_shift_num(self, shift_num):
self.__shift_num = shift_num
def set_pay_rate(self, pay_rate):
self.__pay_rate = pay_rate
def get_shift_num(self):
return self.__shift_num
def get_pay_rate(self):
return self.__pay_rate
#This program creates an instance of Employee Class
#and an instance of Production Worker Class:
again = 'Y'
while again.upper() == 'Y':
print('Enter the following data for the employee: \n')
name = input('What is the employee name?: ')
number = input('What is the employee number? ')
shift_num = input('What is the employee shift number? 1 = Day, 2 = Night :')
while shift_num != '1' and shift_num != '2':
shift_num = input('Invalid entry! Enter 1 for Day shift or 2 for Night shift!')
else:
if shift_num == '1':
shift_num = 'Day'
if shift_num == '2':
shift_num = 'Night'
pay_rate = float(input('What is the employee pay rate? '))
print()
print('This is an instance of the Employee class:')
employee = Employee(name, number)
print('EMPLOYEE: \t\t'+ employee.get_name())
print('EMPLOYEE NUMBER: \t' + employee.get_number())
print()
print('This is an instance of the Production Worker class: ')
prodworker = employee.ProductionWorker(shift_num, pay_rate)
print('SHIFT: \t\t\t' + ProductionWorker.get_shift_num())
print('PAY RATE: \t\t$' + format(ProductionWorker.get_pay_rate(), ',.2f'), sep='')
print('--------------------------------------------')
again = input('Enter Y to add another: ')
if again.upper() != 'Y':
print('Program End')
The ProductionWorker class is a subclass of the Employee class, but that doesn't mean you can call it through an instance of Employee. It's still a top-level class that you should call directly. Try replacing employee.ProductionWorker(...) with just ProductionWorker(...).
You'll get past the current error, but you may have new ones. For instance, I think the current attempt to call Employee.__init__ from ProductionWorker.__init__ will fail because it doesn't pass the right number of arguments. You may also have logic issues, if you expected employee.ProductionWorker to create a ProductionWorker instance that was related in some way to the employee object.
I'd also discourage you from using __double_leading_underscore names for your attributes. That invokes Python's name mangling system, which is mostly intended to help prevent accidental reuse of the same name from different classes in a large or unpredictable inheritance hierarchy. If you just want your attributes to be "private", use a single underscore. That doesn't protect them from being accessed by outside code, but it serves as documentation that they're not part of the object's public API. One of Python's design philosophies is that it's programmers are responsible for their own behavior (often described with the phrase "We're all consenting adults"). If a programmer wants to access an object's private data they can do so (which can be very useful for debugging). But if they break stuff, they have no one to blame but themselves.
I am new to Python, am just learning Classes, and am trying to write a "personal info" program:
This is my code:
class PersonalInfo():
def names(self, name):
name = raw_input("What is your name?")
self.names = name
def addresses(self, add):
add = raw_input("What is your adress?")
self.addresses = add
def ages(self, age):
age = raw_input("What is your age?")
self.ages = age
def numbers(self, number):
number = raw_input("What is your phone number?")
self.numbers = number
PersonalInfo()
def print_names():
info = PersonalInfo()
print "Name:", info.names(name)
print "Address:", info.addresses(add)
print "Age:", info.info.ages(age)
print "Phone number:", info.numbers(number)
print_names()
But when I run it it says this:
NameError: global name 'add' is not defined
Can someone please help me?
There are several issues with your code other than the NameError and I strongly suggest you read more on python classes:
https://docs.python.org/2/tutorial/classes.html
https://www.tutorialspoint.com/python/python_classes_objects.htm
https://en.wikibooks.org/wiki/A_Beginner's_Python_Tutorial/Classes
I'll run you through those issues.
First, the NameError occurs because the add variable was not defined. The same applies to all other arguments you provided in your print statements.
Second, there are issues with the way you define the class methods:
class PersonalInfo():
def names(self, name):
name = raw_input("What is your name?")
self.names = name
Here, you are re-assigning the name variable to the return value of raw_input so there's no sense in setting it as an argument in the first place. Also, by stating self.names = name you are re-assigning the class method to the string that is returned by raw_input!
Third, you have to decide whether you want to provide the information when calling the methods, or using raw_input. Here's a working example of your code, assuming you want to use raw_input
class PersonalInfo():
def names(self):
name = raw_input("What is your name?")
self.name = name
def addresses(self):
add = raw_input("What is your adress?")
self.address = add
def ages(self):
age = raw_input("What is your age?")
self.age = age
def numbers(self):
number = raw_input("What is your phone number?")
self.number = number
def print_names():
info = PersonalInfo()
# Get information
info.names()
info.addresses()
info.ages()
info.numbers()
# After getting the info, print it
print "Name:", info.name
print "Address:", info.address
print "Age:", info.age
print "Phone number:", info.number
print_names()
In my intro class, we just started the section on object-oriented programming. This class is the first I've ever been exposed to programming, and I'm really not understanding it.
We have an assignment where we have to create an Animal class, a Zoo class, and then a zookeeper program to run the information from the first two classes. I have the programs typed up based off of examples in my book, but am still not doing it correctly.
If you could look over my codes and give me some feedback or help, that would be greatly appreciated!
class Animal:
def __innit__(self, animal_type, name):
self.animal_type = animal_type
self.name = name
def get_animal_type(self, animal_type):
self.__animal_type = animal_type
def get_name(self, name):
self.__name = name
def check_mood(self, mood):
input random.txt
print random.random()
Class Zoo:
def __innit__(self):
self.__animals = animal_list
def add_animals(self, animal):
self.__animals.append(animal)
def show_animals(animal_list):
return animal_list
input Animal.py
input Zoo.py
def main():
ADD_ANIMAL = 1
SHOW_ANIMALS = 2
EXIT = 3
def get_manu_choice():
print()
print("Zoo Options")
print("-----------")
print("1. Add Animal")
print("2. Show Animals")
print("3. Exit")
print()
choice = int(input("What would you like to do? "))
while choice < ADD_ANIMAL or choice > EXIT:
choice = int(input("Please choose a valid option: "))
return choice
main()
innit should be init
Looks to me like you are missing a chunk of functionality. You need an instance of zoo, and then in response to the input, either add another animal to the zoo or print the list of animals.