Hello so im new to python and im in progress to learning class and function. I keep getting this error code, i don't know whats wrong on my code. Here is the source code:
class Data:
def __init__(self,nama):
self.nama=nama
def __private(self):
self.ganti="Replace"
def ganti(self):
self.prvt=self.ganti
print(self.prvt)
class User(Data):
def __init__(self,nama):
self.nama=nama
super().__init__
def printUsername(nama):
print(nama)
user1 = User("Test")
user1.printUsername()
user1.ganti()
user1.printUsername()
When i run, the output is like this:
<__main__.User object at 0x000002C1B781D310>
<bound method Data.ganti of <__main__.User object at 0x000002C1B781D310>>
<__main__.User object at 0x000002C1B781D310>
Press any key to continue . . .
So whats wrong on my code? I excpeted the output is:
Test
Replace
You have some Syntax error in your code.
Variable name and function name shouldn't be the same.
When a variable is defined in init, all functions use it and there is no need to redefine it. Even when a class inherits from another class.
This code will print the output you want.
class Data:
def __init__(self, nama):
self.nama = nama
self.ganti = "Replace"
self.prvt = self.ganti
def Ganti(self):
print(self.prvt)
def __private(self):
pass
class User(Data):
"""
def __init__(self):
super().__init__()
# because we don't have new variable to define, we can remove this function.
"""
def printUsername(self):
print(self.nama)
User('Test').printUsername()
User('Test').Ganti()
Related
class A():
B: str = "no"
class test(A):
a = None
def __init__(self, val):
self.a = val
if self.a == "test":
B = "yes"
t = test("test")
print(t.B)
NameError: name 'self' is not defined
self.a shows an error so how can I access a which was assigned a value in the constractor out side of a method inside the class?
Because you are making class object u need to define the object name used
class test():
def __init__(self):
You want to access your attribute, you cant access outside of method so
class test():
def __init__(self):
self.a = "test"
if self.a == "test":
pass
or you can create another method that process that
class test():
def __init__(self):
self.a = "test"
self.access_a()
def access_a(self):
if self.a == "test":
print("do something")
pass
What you are asking for (given that your example defines an instance attribute) is quite frankly not possible, you can't access an instance attribute without referencing that instance and you can't reference an instance of a class in its body.
What could be done is changing the class attribute from the constructor but that would be pointless because all code in the body of the class gets executed first so such a check (as in your provided sample) would be pointless anyways.
The first code work properly but when I declare the 'toStr' function(or method) inside the class I get error. What's wrong with this code?
First Code:
class Test:
def __init__(self,hour,minute,second):
self.hour=hour
self.minute=minute
self.second=second
# Return String Time Format
def toStr(self):
return str(self.hour)+":"+str(self.minute)+":"+str(self.second)
t=Test(10,20,50)
print(toStr(t))
The second code with NameError:
class Test:
def __init__(self,hour,minute,second):
self.hour=hour
self.minute=minute
self.second=second
# Return String Time Format
def toStr(self):
return str(self.hour)+":"+str(self.minute)+":"+str(self.second)
t=Test(10,20,50)
print(toStr(t))
Here is my code,
class Test:
def __init__(self,hour,minute,second):
self.hour=hour
self.minute=minute
self.second=second
# Return String Time Format
def toStr(self):
return str(self.hour)+":"+str(self.minute)+":"+str(self.second)
t=Test(10,20,50)
print(t.toStr())
here is my output,
10:20:50
You can't call the toStr function outside the t object (Test class), you need to call it using the dot operator because the toStr function belongs to the Test class now.
You need to either call the method on the object like:
print(t.toStr())
or
print(Test.toStr(t))
-> As you are working with object-oriented concepts. you should be familiar with it. whenever you create a class you have to create object of it to use its functionality
class MyTest: #class
def __init__(self, hour, minute, second): #constructor
self.hour=hour
self.minute=minute
self.second=second
def toStr(self): #method
return str(self.hour)+":"+str(self.minute)+":"+str(self.second)
obj=MyTest(4,5,5) # class object
print(obj.toStr()) # to call toStr() method you have to use it with a object.
I'm trying to access to an attribute in a method, from another method. They are all in one class.
It's like following.
class A:
def __init__(self, a):
self.a = a
def meth(self):
attr= 'yo'
return ''
def here(self):
another = self.meth.attr
return another
example = A('a')
print(example.here)
What I'm intending is this should print 'yo'. But it returns error sign
NameError: name 'yo' is not defined
you know, If it were not inside the class, we can access any attribute of a function from another. for example, the following code make sense.
def fun1():
fun1.var = 100
print(fun1.var)
def fun2():
print(fun1.var)
print(fun1.var) >> "100"
And I also notice that we can access attribute in the init function. But I want to access attr in ohter methods.
Is there anyway to do things like this
Hi everyone i wanna use a calculated value from a method of the class itself for the rest of the class methods but it must calculate once for all and i need to invoke method inside the class itself i write an example:
class something():
def __init__():
pass
def __sum(self, variable_1, variable_2):
self.summation = sum(variable_1, variable_2)
# I need to calculate summation here once for all:
# how does the syntax look likes, which one of these are correct:
something.__sum(1, 2)
self.__sum(1, 2)
# If none of these are correct so what the correct form is?
# For example print calculated value here in this method:
def do_something_with_summation(self):
print(self.summation)
Something like this seems to be what you're looking for:
class Something:
def __init__(self):
self.__sum(1, 2)
def __sum(self, variable_1, variable_2):
self.summation = sum(variable_1, variable_2)
Not saying this is the ideal approach or anything, but you haven't really given us much to go off of.
In general, make sure self is the first argument in all class methods, and you can call that class method at any time using either self.method_name() if you are using it from within another class method or instance.method_name() if you're using it externally (where instance = Something()).
Assuming that you would receive variable1 and variable2 when you instantiate the class one solution could be:
class something():
def __init__(self, variable1, variable2):
self.summation = variable1 + variable2
def do_something_with_summation(self):
print(self.summation)
If instead you're creating variable1 and variable2 inside other methods, then you could make them class variables:
class Something():
def __init__(self):
#Put some initialization code here
def some_other_method(self):
self.variable1 = something
self.variable2 = something
def sum(self):
try:
self.summation = self.variable1 + self.variable2
except:
#Catch your exception here, for example in case some_other_method was not called yet
def do_something_with_summation(self):
print(self.summation)
Got the code like below:
class Type:
def __init__(self, index):
self.index = index
class MyCls(Type):
def __init__(self, index):
super(MyCls, self).__init__(index)
And after trying to compile - got next error message on the super line:
Detail NameError: global name 'MyCls' is not defined
How should I define MyCls to make the above code work?
The snippet you've shown shouldn't trigger a NameError - classes are allowed to refer to themselves in this way
However, super only works with new-style classes - trying to instantiate a MyCls object will raise a TypeError. To fix this, the class Type needs to explicitly inherit from object:
class Type(object):
def __init__(self, index):
self.index = index
MyCls can stay as it is in this case. Then you have:
>>> a = MyCls(6)
>>> a
<__main__.MyCls object at 0x7f5ca8c2aa10>
>>> a.index
6