Trying to call a function within class but its not working [duplicate]

2024/10/11 10:16:56

I am trying to call a function but it's not working. here is the code:

class Compagnie:def __init__(self, nom, actions, prix):self.nom = nomself.actions = actionsself.prix = prixdef setActions(self):print("Changer le nombre d'actions pour " + self.actions)

I did:

Compagnie.setActions(50)

and i'm getting this error : AttributeError: 'int' object has no attribute 'actions'

What am I doing wrong?

Answer

Classes can contain three types of methods:

  1. Instance methods, e.g.

    def imethod(self,...): ...
    

    These can be called only on an instance of a class, and can access class and instance attributes. The first parameter is traditionally called self and is automatically passed to the method when called on an instance:

    instance = Class()
    instance.imethod(...)
    
  2. Class methods, e.g.

    @classmethod
    def cmethod(cls,...): ...
    

    These can be called on the class itself or instances, but can only access class attributes. The first parameter is traditionally named cls and is automatically passed to the method when called on a class:

    Class.cmethod(...)
    instance.cmethod(...)  # works, but can't access instance attributes.
    
  3. Static methods, e.g.

    @staticmethod
    def smethod(...): ...
    

    These are functions related to the class, but can't access instance or class attributes, so they are not passed the class or instance object as the first parameter. They can be called on an instance or a class:

    instance = Class()
    Class.smethod(...)
    instance.smethod(...)
    

Example (Python 3.9):

class Demo:cvar = 1def __init__(self,ivar):self.ivar = ivar@classmethoddef cmethod(cls):print(f'{cls.cvar=}')@staticmethoddef smethod():print('static')def imethod(self):print(f'{self.cvar=} {self.ivar=}')Demo.smethod()
Demo.cmethod()
instance = Demo(2)
instance.smethod()
instance.cmethod()
instance.imethod()

Output:

static
cls.cvar=1
static
cls.cvar=1
self.cvar=1 self.ivar=2

In your case, you defined an instance method, but didn't create an instance first, so the int parameter you tried to pass was passed as self, and internally tried to access actions on the integer 50. Create an instance first, and don't pass it any parameters. self will be automatically passed:

compagnie = Compagnie('nom','actions','prix')
compagnie.setActions()
https://en.xdnf.cn/q/118335.html

Related Q&A

Tkinter Label not showing Int variable

Im trying to make a simple RPG where as you collect gold it will be showed in a label, but it doesnt!! Here is the code:def start():Inv=Tk()gold = IntVar(value=78)EtkI2=Label(Inv, textvariable=gold).pa…

How to refer a certain place in a line in Python

I have this little piece of code:g = open("spheretop1.stl", "r") m = open("morelinestop1.gcode", "w") searchlines = g.readlines() file = "" for i, line…

List comprehension output is None [duplicate]

This question already has answers here:Python list comprehension: list sub-items without duplicates(6 answers)Closed 8 years ago.Im new to python and I wanted to try to use list comprehension but outco…

error while inserting into mysql from python for loop [duplicate]

This question already has answers here:Closed 12 years ago.Possible Duplicate:convert list to string to insert into my sql in one row in python scrapy Is this script correct. I want to insert the scra…

Half of Matrix Size Missing

I wanted to ask why is it that some of my matrices in Python are missing a size value? The matrices/arrays that re defined show the numbers in them, but the size is missing and it is throwing me other…

Clicking Side Panel Elements in Selenium Without IFrames

I want to download U.S. Department of Housing and Urban Development data using Pythons Selenium. Heres my code. import os from selenium import webdriver from webdriver_manager.chrome import ChromeDrive…

Library to extract data from open Excel workbooks

I am trying to extract data from workbooks that are already open. I have found the xlrd library, but it appears you can only use this with workbooks you open through Python. The workbooks I will use in…

Keras apply different Dense layer to each timestep

I have training data in the shape of (-1, 10) and I want to apply a different Dense layer to each timestep. Currently, I tried to achieve this by reshaping input to (-1, 20, 1) and then using a TimeDis…

Create a pass-through for an installed module to achieve an optional import

Im writing a library in python 3.7. Id like it to have as few dependencies as possible. For example, tqdm is nice to have but ideally Id like my library to work without it if its not there. Therefore, …

Django, Redis: Where to put connection-code

I have to query redis on every request in my Django-app. Where can I put the setup/ connection routine (r = redis.Redis(host=localhost, port=6379)) so that I can access and reuse the connection without…