Getting a class attribute in a method - python

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

Related

Add argument to function after it's already been called?

For example, if I have the function:
def to_full_name(first_name, last_name=None): # Note that 'last_name' is not required, so an error will not occur
return '{} {}'.format(first_name, last_name)
# ...
a = to_full_name('John')
How can I add the second argument to the 'a' variable later down the line? ex:
a.set_argument('last_name', 'Doe')
For this particular problem I would recommend a class.
class Person:
def __init__(self, first_name=None, last_name=None):
self.first_name = first_name
self.last_name = last_name
def set_first_name(self, name):
self.first_name = name
def set_last_name(self, name):
self.last_name = name
def to_full_name():
return '{} {}'.format(self.first_name, self.last_name)
Then we change it as follows
person = Person("John")
person.set_last_name("Doe")
print(person.to_full_name())
We can also change the values directly
person = Person()
person.last_name = "Doe"
person.first_name = "John"
print(person.to_full_name())

Python Class related error?

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

Initializing Python class object with external data

Suppose a "person" class contains name, age and phone number.
When creating a person object, I would like to set phone number by looking up an external phone book rather than explicitly passing a phone number.
Option 1: Store phone book as a class variable
class person():
phonebook = {}
def __init__(self, name, age):
self.name = name
self.age = age
self.phone = self.phonebook[self.name]
person.phonebook = {'dan':1234}
dan = person('dan', 30)
Option 2: Create a class object without phone number then have a separate function to load it.
class person():
def __init__(self, name, age):
self.name = name
self.age = age
def loadphone(self, phone):
self.phone = phone
phonebook = {'dan':1234}
dan = person('dan',30)
dan.loadphone(phonebook['dan'])
Both solutions do not seem optimal. Option 1, every person carries a phone book (unnecessarily). Option 2 requires 2-step initialization.
Is there a better way to create a person object without 1) explicitly passing a phone number or phone book during initialization, 2) storing phone book as a class variable, and 3) requiring a multi-step initialization?
As discussed in this post, defining a variable outside of any methods in the class, while still being defined in a class makes it a static variable, such as the one you have:
class person():
phonebook = {}
This means that there is a single phonebook which all instances of the class refer to
person.phonebook{'dave':1234, 'joey':5678}
dave = person('dave', 30)
joey = person('joey', 23)
There is still only the one universal phonebook that all instances refer to. The one thing to change in that code is that you should not define it as self.phonebook['dave'] so it should look like
class person():
phonebook = {}
def __init__(name, age):
self.name = name
self.age = age
self.number = phonebook[name]
Are you wanting to optionally define a phone number for a Person? You could do something like below:
class Person():
def __init__(self, name, age, phone=None):
self.name = name
self.age = age
self.phone = phone
dan = Person('dan',30, phone=1234)
stan = Person('stan', 60)
Firstly, as for me, it's too wide question and very depend on task. In one case you can access to PhoneBook, in another - it's bad idea (e.g. PhoneBook load data from server and creating 1000 of Person will produce 1000 requests).
Secondary, their is next approach:
class BasicPerson():
def __init__(self, name, age):
self.name = name
self.age = age
def ToString(self):
return('some code')
class PersonWithPhone():
def __init__(self, basicPerson, phone):
self.basicPerson = basicPerson
self.phone = phone
def ToString(self):
return('another code ' + self.basicPerson.ToString())
person = PersonWithPhone(BasicPerson('', ''), '11111')
It's just example and may seems useless, but in many situations you can extract some core actions (ToString, for example) and than wrote small decorators that expand each other.

Creating objects in Python way

I'm learning Python and recently started with the OOP part.
I know there are different ways to create objects but I do not know what way I should aim at.
Create objects with arguments or without arguments?
Then I do understand the best way to change the attributes is with method calls.
Code:
class Human(object):
def __init__(self):
self.name = ''
self.age = 0
def set_name(self, name):
self.name = name
def set_age(self, age):
self.age = age
class Humans(object):
def __init__(self, name, age):
self.name = name
self.age = age
def set_names(self, name):
self.name = name
def set_ages(self, age):
self.age = age
# Create object without arguments
boy = Human()
boy.set_name('Peter')
boy.set_age(30)
# Or create object with arguments
girl = Humans('Sandra', 40)
An object should be in an usable state after creation. That said, a human with no name and no age is not useful. So the second implemention is preferred. Another thing is, that you don't need setters in python, which reduces the class to
class Humans(object):
def __init__(self, name, age):
self.name = name
self.age = age

TypeError: __init__() takes exactly 4 arguments (1 given)

I need help , I have the following classes in Python with inheritance and I have an error:
class Human:
def __init__(self,name,surname,age):
self.name = name
self.surname = surname
self.age = age
def getName(self):
return self.name
def getSurname(self):
return self.surname
def setName(self, name):
self.name = name
def setSurname(self, surname):
self.surname = surname
def setAge(self, age):
self.age = age
def getAge(self):
return self.age
pass
and:
from Human import Human
class Student(Human):
def __init__(self,name,surname,age,file):
Human().__init__(self,name, surname, file)
self.file = file
def getFile(self):
return self.file
def setFile(self, file):
self.file = file
pass
When I instantiate me the following error
from Student import Student
student1 = Student("Jhon", "Santana", "20", "111000")
Error:
Human().__init__(self, name, surname, age)
TypeError: __init__() takes exactly 4 arguments (1 given)
which is the cause of this error? Thanks...
Human().__init__(self,name, surname, age)
thats not how you create an instance of your class
you should do:
Human.__init__(self,name, surname, age)
without the () .otherwise you try to create an instance of it in Human()
dont instanciate your parent class
def __init__(self,name,surname,age,file):
Human.__init__(self,name, surname, file)
or even better
super(Human,self).__init__(name,surname,age)
Try this:
class Human:
def __init__(self,name,surname,age):
self.name = name
self.surname = surname
self.age = age
def getName(self):
return self.name
def getSurname(self):
return self.surname
def setName(self, name):
self.name = name
def setSurname(self, surname):
self.surname = surname
def setAge(self, age):
self.age = age
def getAge(self):
return self.age
class Student(Human):
def __init__(self, name,surname,age,file):
super().__init__(name, surname, age)
self.file = file
def getFile(self):
return self.file
def setFile(self, file):
self.file = file
student1 = Student("Jhon", "Santana", "20", "111000")
input()
When you inherit another class but want to overwrite some of the attributes, you need to add the parent class's attributes that you want to overwrite in the super constructor so that the attributes passed into the student class can be passed straight into the parent class.
Feel free to watch my video on inheritance at the following address:
https://www.youtube.com/watch?v=cqRtcmPGcic
As detailed here, the use of super is prefered:
def __init__(self, name, surname, age, file):
super(Human, self).__init__(name, surname, age)
self.file = file

Categories