why is the instance attribute defined three times in python: once in the parenthesis, once in with the self keyword and once in the assignment
class Details():
def __init__(self,name,age):
self.name = name
self.age = age
__init__ is a function/method and like any other functions has "local variables" just like :
def fn(a, b):
print(a, b)
In your example, name, age in parameters and in right hand side of the assignments are just like a and b. You can choose any name you want for these variables.
But the name and age which are parts of self.name and self.age statements respectively, are attributes of your new-created instance(which self points to it). The name you choose for this attributes will exist in instance's __dict__(instance's namespace dictionary), so that's how you can call them later.
class Details:
def __init__(self, name, age):
self.name = name
self.age = age
obj = Details('John', 20)
print(obj.name)
print(obj.age)
__init__ is the constructor (in OOP terms) to create Details object. in Python, a constructor's first parameter is always self.
self points to the newly created object. It got two attributes, name and age.
the parameters, name and age inside parentheses, can have different names as well. So, the following code works the same :
class Details():
def __init__(self,n,a):
self.name = n
self.age = a
Related
I have written code to count employees using class but the the code doesn't work.
class employee:
empCount = 0;
def employee(self, name, salary):
self.name = name;
self.salary = salary;
employee.empCount += 1;
def displayCount(self):
print ("\nTotal Employee %d", Employee.empCount);
def displyEmployee(self):
print('Name:',self.name,'Salary:',self.salary);
emp1 = employee('ABS', 2000)
Your code has a number of problems that are preventing it from working as you expect:
You did not declare your constructor properly. When you do employee('ABS', 200), Python looks for a function called __init__ on the class object. You declared your constructor as employee, similarly to how you would do so in C-based languages. This won't work.
You store the employee count as a variable scoped to the class object. You can do this but I wouldn't because it's a misuse of that capability. Instead, you should create a list of employees and get the length of the list.
Instead of declaring display functions, you should overload the __str__ function, which returns a string representing the object.
Class names should be PascalCase (this doesn't keep your code from working but you should definitely address it).
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def __str__(self):
return f"Name: {self.name}, Salary: {self.salary}"
employees = []
employees.append(Employee('ABS', 200))
len(employees) # 1
I am trying to characterise my class with init but the website says I have to add the last two lines of code but I don't know what they do? Could someone explain?
Code:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("My awesome name is " + self.name)
p1 = Person("bob", 69)
p1.myfunc()
It is pretty simple. Let's say you create a string.
a = "Hello"
This basically creates a new string object called a. Now you can use a variety of functions like .isdigit(), .isalnum() etc. These functions are basically the functions of the String class and when called, they perform the function in relation to the object they are associated with.
So Saying,
print(a.isalnum())
Would give True as the function is defined to check of the String object is alphanumeric.
In the same way,
p1 = Person("bob", 69)
p1.myfunc()
First-line creates a new Person object with name='bob' and age=69. The second line then calls the function myfunc() in association with the Person p1 and executes with the attributes of p1 as its own local variables.
The first chunk of code is defining a class. This says what the class should be called, what attributes it has, and defines its behaviour.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("My awesome name is " + self.name)
Once those lines are run, the class exists in your session, but no instances of it do.
This creates an instance of the class:
p1 = Person("bob", 69)
And this line is that instance calling its method myfunc():
p1.myfunc()
I have an class Student which has an array(list) of Objects called Students. I am trying to output the names of all the students in the array.
class Student(object):
name = ""
age = 0
major = ""
# The class "constructor" - It's actually an initializer
def __init__(self, name, age, major):
self.name = name
self.age = age
self.major = major
Students = []
Students.append(Student("Dave",23,"Chem"))
Students.append(Student("Emma",34,"Maths"))
Students.append(Student("Alex",19,"Art"))
print(Students[0].__dict__)
print(Students[1].__dict__)
print (Students[0])
Both the ways I have found and tired do not output the specific name but the location or the whole object. Is there a way to just output the name? For example output Students[0] name Dave
{'name': 'Emma', 'age': 34, 'major': 'Maths'}
<__main__.Student object at 0x000001FCDE4C2FD0>```
If you just want the name, you can print(Students[0].name). If you want to see the relevant attributes when printing a Student object, you can implement the __repr__ method.
class Student:
# The class "constructor" - It's actually an initializer
def __init__(self, name, age, major):
self.name = name
self.age = age
self.major = major
def __repr__(self):
return f"<Student name={self.name} age={self.age} major={self.major}>"
This way you can simply do print(Students[0]) to see the name, age and major of a student.
By the way, for a normal class definition, you want to initialize instance attributes inside the __init__ method, instead of declaring them above __init__: those are class attributes. Please read this section of the documentation to familiarize yourself with the syntax.
I've tried to make an OOP based program in python. I gave it an object to work with and tried to make it print the name, but its not working.
class human:
def __init__(self, name):
print("this is a human")
def name(self, name):
print("this is {}".format(bob.name))
bob = human("bob")
Anyone know what the problem could be?
Beyond the answers you already received (which solve your problem), I'd suggest not having a method that prints the name. Rather, you should have a __str___ dunder method that defines the object's behavior when an instance is printed.
class human:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
person = human("bob")
print(person)
'bob'
You can also define the object's behavior when the instance name is entered in the console, for instance just running the line
>>> person
You can do it with __repr__:
def __repr__(self):
return f'when entering the instance name in the console: {self.name}'
This will print:
when entering the instance name in the console: bob
This appears more pythonic to me than having a method that simply prints the name.
You're never storing the name on the instance, where would it get the name from? Your __init__ needs to do something along the lines of self.name = name
the name method and attribute are going to conflict, the latter will shadow (hide) the former, and it should look up whatever attribute its using on self
You never assigned the passed name to the object. Try:
class human:
def __init__(self, name):
print("this is a human")
self.name = name
def print_name(self):
print("this is {}".format(self.name))
bob = human("bob")
bob.print_name()
there are couple of things to update in the code:
bob is an instance which is not defined at human class
notice that init, name functions expect external param but you never use it in the function. (in self. = name)
in order to use it:
define a var in the class named 'name' and update you function to:
class human:
_name = ""
def __init__(self, name):
print("this is a human")
self._name = name
def name(self):
print("this is "+ self._name)
bob = human("bob")
bob.name()
bob = human("bob") only init function and you should call bob.name() in order to call the print-name function
I'm trying to learn python and I now I am trying to get the hang of classes and how to manipulate them with instances.
I can't seem to understand this practice problem:
Create and return a student object whose name, age, and major are
the same as those given as input
def make_student(name, age, major)
I just don't get what it means by object, do they mean I should create an array inside the function that holds these values? or create a class and let this function be inside it, and assign instances? (before this question i was asked to set up a student class with name, age, and major inside)
class Student:
name = "Unknown name"
age = 0
major = "Unknown major"
class Student(object):
name = ""
age = 0
major = ""
# The class "constructor" - It's actually an initializer
def __init__(self, name, age, major):
self.name = name
self.age = age
self.major = major
def make_student(name, age, major):
student = Student(name, age, major)
return student
Note that even though one of the principles in Python's philosophy is "there should be one—and preferably only one—obvious way to do it", there are still multiple ways to do this. You can also use the two following snippets of code to take advantage of Python's dynamic capabilities:
class Student(object):
name = ""
age = 0
major = ""
def make_student(name, age, major):
student = Student()
student.name = name
student.age = age
student.major = major
# Note: I didn't need to create a variable in the class definition before doing this.
student.gpa = float(4.0)
return student
I prefer the former, but there are instances where the latter can be useful – one being when working with document databases like MongoDB.
Create a class and give it an __init__ method:
class Student:
def __init__(self, name, age, major):
self.name = name
self.age = age
self.major = major
def is_old(self):
return self.age > 100
Now, you can initialize an instance of the Student class:
>>> s = Student('John', 88, None)
>>> s.name
'John'
>>> s.age
88
Although I'm not sure why you need a make_student student function if it does the same thing as Student.__init__.
Objects are instances of classes. Classes are just the blueprints for objects. So given your class definition -
# Note the added (object) - this is the preferred way of creating new classes
class Student(object):
name = "Unknown name"
age = 0
major = "Unknown major"
You can create a make_student function by explicitly assigning the attributes to a new instance of Student -
def make_student(name, age, major):
student = Student()
student.name = name
student.age = age
student.major = major
return student
But it probably makes more sense to do this in a constructor (__init__) -
class Student(object):
def __init__(self, name="Unknown name", age=0, major="Unknown major"):
self.name = name
self.age = age
self.major = major
The constructor is called when you use Student(). It will take the arguments defined in the __init__ method. The constructor signature would now essentially be Student(name, age, major).
If you use that, then a make_student function is trivial (and superfluous) -
def make_student(name, age, major):
return Student(name, age, major)
For fun, here is an example of how to create a make_student function without defining a class. Please do not try this at home.
def make_student(name, age, major):
return type('Student', (object,),
{'name': name, 'age': age, 'major': major})()
when you create an object using predefine class, at first you want to create a variable for storing that object. Then you can create object and store variable that you created.
class Student:
def __init__(self):
# creating an object....
student1=Student()
Actually this init method is the constructor of class.you can initialize that method using some attributes.. In that point , when you creating an object , you will have to pass some values for particular attributes..
class Student:
def __init__(self,name,age):
self.name=value
self.age=value
# creating an object.......
student2=Student("smith",25)