This question already has an answer here:
How to use class name in class scope?
(1 answer)
Closed 3 years ago.
I'm trying to run a class named person. The error is name 'person' is not defined. How can I solve this problem?
class person:
person.count = 0
def __init__(self,gender,location,DOB):
# this is constructor method
self.__gender = gender
self.__location = location
self.__DOB = DOB
# to make the variable inaccessible from out of the class
# we have to prefix it with at least two underscores
print(person.__self)
print(person.__DOB)
person.count += 1
def getname(self):
#this is access method
return person.__self
def getDOB(self):
return person.__DOB
def _del_(self):
print('deleted')
First of all, put the line person.count = 0 inside __init__. Next, change every person to self (unless it's the class definition).
Related
This question already has answers here:
How to print instances of a class using print()?
(12 answers)
What is the difference between __str__ and __repr__?
(28 answers)
How can I choose a custom string representation for a class itself (not instances of the class)?
(7 answers)
Closed 1 year ago.
I wrote some code and was not sure how to make it work as expected,
class Bee():
def __init__(self, name, identifier):
self.name = name
self.identifier = identifier
bee = Bee(name='Bumble', identifier=1)
print(str(bee))
->> Should Print: 1 Bumble
I thought of creating a function in Class Bee as follows:
def get_hive(self):
return '{} {}'.format(self.identifier, self.name)
However, I am not sure how, when I create an object of class Bee, to assign given attributes instead of address of the memory cell.
My code currently ofc prints smth like: <main.Bee object at 0x000001EA24F49460> instead of the attributes.
If you want str(bee) to return a string as you describe, implement a __str__ method:
class Bee():
def __init__(self, name: str, identifier: int):
self.name = name
self.identifier = identifier
def __str__(self) -> str:
return f"{self.identifier} {self.name}"
bee = Bee('Bumble', 1)
print(bee)
prints:
1 Bumble
Note that print will automatically call str on any parameter that's not already a str, so you can just say print(bee) instead of print(str(bee)).
This question already has answers here:
Calling a variable from another method in the same class [duplicate]
(1 answer)
How to put my function in to class.Beginner
(1 answer)
Closed 3 years ago.
The sample code is below.
I am trying to get the inputted value for the 'name' variable from the first method and use it to print a message using the second method (method2).
I would appreciate any advice on how to do this or alternative ways to go about it.
class User:
method1(self):
name = input("Enter name")
method2(self):
greeting = print("Hello", name)
Please check What __init__ and self do on Python?
You should assign the input string to class variable
method1(self):
self.name = input("Enter name")
and then you can use it in other method.
method2(self):
greeting = print("Hello", self.name)
Greetings!
#
class User():
def method1(self):
self.name = input('Enter your name:')
def method2(self):
print("Name is", self.name )
obj = User()
obj.method1()
obj.method2()
#
Also read this
https://www.geeksforgeeks.org/self-in-python-class/
This question already has answers here:
How to avoid having class data shared among instances?
(7 answers)
Closed 3 years ago.
Hello Just curious on why the second instance already gets the category that was added in the first instance creation. How can i fix it?
class Game_record:
category = []
def __init__(self,name):
self.name = name
def add_category(self, cat):
self.category.append(cat)
def reset_cat(self):
self.category = []
def ret_cat(self):
return self.category
game = ["a","b"]
for each in game:
g = Game_record( each )
g.add_category("kol")
g.add_category("bol")
print(g.ret_cat())
g.reset_cat()
print(g.ret_cat())
output
['kol', 'bol']
[]
['kol', 'bol', 'kol', 'bol']
[]
To fix it declare category in __init__(), e.g.:
class Game_record:
def __init__(self,name):
self.name = name
self.category = []
...
The reason why you observe that behavior is that if you declare category right after the class, it becomes a class-level attribute rather than an object-level attribute.
This question already has answers here:
Python - Classes and OOP Basics
(6 answers)
Closed 5 years ago.
Could anyone help with my understanding, please? I don't understand what is happening with this line or why it works : course_running.add_student(self).
I thought this was an OOP concept but could anyone help make this clearer?
class Student:
def __init__(self, name, student_number):
self.name = name
self.student_number = student_number
self.classes = []
def enrol(self, course_running):
self.classes.append(course_running)
course_running.add_student(self)
class CourseRunning:
def __init__(self, course, year):
self.course = course
self.year = year
self.students = []
def add_student(self, student):
self.students.append(student)
course_running is an object of class CourseRunning and course_running.add_student(self) is calling a method of it's class named add_student which is appending the student to students list.
Your enrol() function in the Student class is taking two parameters: self and course_running.
self is the instance of your current class (Student).
That's why in your add_student() function (which takes also two parameters: self (the current instance of the CourseRunning class) and student (which is simply an instance of a Student)).
That's why you can pass the self from enrol() as student in add_student().
This question already has answers here:
Getting the name of a variable as a string
(32 answers)
Closed 6 years ago.
Is there a way to get the name under which a variable or a property is stored?
Something like:
class X:
def __init__(self):
self.name = __name_under_which_I_m_stored__
jeff = X()
print(jeff.name) # yields 'jeff'
Pretty sure that this is not possible, but you never know... Furthermore, I'm aware that the name could be unspecified (do_something(X())) or ambiguous (jeff=frank=X()).
The Python VM has no way to know the literal name of a name. For objects, you can access the name via __name__ attribute.
If you want to do this, you'll need to implement a mapping of names to values. You can do this with a dict.
class X:
def __init__(self):
self.names = {};
def set(self, name, value):
self.names[name] = value
def get(self, name):
return (name, self.names[value])
jeff = X()
jeff.set("name", "jeff");
print(jeff.get("name")) # yields ("name", "jeff")